import {
  boolean,
  int,
  timestamp,
  mysqlTable,
  primaryKey,
  varchar,
} from "drizzle-orm/mysql-core"
import type { AdapterAccountType } from "next-auth/adapters"
import { users } from "@/schema/users"

export const accounts = mysqlTable(
  "accounts",
  {
    userId: varchar({ length: 255 })
      .notNull()
      .references(() => users.id, { onDelete: "cascade" }),
    type: varchar({ length: 255 })
      .$type<AdapterAccountType>()
      .notNull(),
    provider: varchar({ length: 255 }).notNull(),
    providerAccountId: varchar({ length: 255 }).notNull(),
    refresh_token: varchar({ length: 255 }),
    access_token: varchar({ length: 255 }),
    expires_at: int(),
    token_type: varchar({ length: 255 }),
    scope: varchar({ length: 255 }),
    id_token: varchar({ length: 2048 }),
    session_state: varchar({ length: 255 }),
  },
  (account) => ({
    compoundKey: primaryKey({
      columns: [account.provider, account.providerAccountId],
    }),
  })
)
 
export const sessions = mysqlTable("sessions", {
  sessionToken: varchar({ length: 255 }).primaryKey(),
  userId: varchar({ length: 255 })
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  expires: timestamp({ mode: "date" }).notNull(),
})
 
export const verificationTokens = mysqlTable(
  "verification_tokens",
  {
    identifier: varchar({ length: 255 }).notNull(),
    token: varchar({ length: 255 }).notNull(),
    expires: timestamp({ mode: "date" }).notNull(),
  },
  (verificationToken) => ({
    compositePk: primaryKey({
      columns: [verificationToken.identifier, verificationToken.token],
    }),
  })
)
 
export const authenticators = mysqlTable(
  "authenticators",
  {
    credentialID: varchar({ length: 255 }).notNull().unique(),
    userId: varchar({ length: 255 })
      .notNull()
      .references(() => users.id, { onDelete: "cascade" }),
    providerAccountId: varchar({ length: 255 }).notNull(),
    credentialPublicKey: varchar({
      length: 255,
    }).notNull(),
    counter: int().notNull(),
    credentialDeviceType: varchar({
      length: 255,
    }).notNull(),
    credentialBackedUp: boolean().notNull(),
    transports: varchar({ length: 255 }),
  },
  (authenticator) => ({
    compositePk: primaryKey({
      columns: [authenticator.userId, authenticator.credentialID],
    }),
  })
)