import { sqliteTable, text, integer, uniqueIndex } from 'drizzle-orm/sqlite-core'

/**
 * Better-Auth 认证四表（user/account/session/verification）。
 * 字段名严格对齐 Better-Auth 官方 schema（驼峰），不自创。
 * 注意：原 db.ts 中 user 表用驼峰字段名（createdAt/updatedAt），
 * 与其它业务表的下划线命名约定不同——保留驼峰以兼容 Better-Auth。
 */
export const user = sqliteTable(
  'user',
  {
    id: text('id').primaryKey(),
    name: text('name').notNull().default(''),
    email: text('email').notNull().unique(),
    emailVerified: integer('emailVerified').notNull().default(0),
    image: text('image'),
    role: text('role').notNull().default('user'),
    banned: integer('banned').notNull().default(0),
    banReason: text('banReason'),
    banExpires: integer('banExpires'),
    phoneNumber: text('phoneNumber'),
    phoneNumberVerified: integer('phoneNumberVerified').notNull().default(0),
    createdAt: integer('createdAt').notNull(),
    updatedAt: integer('updatedAt').notNull(),
  },
)

export type User = typeof user.$inferSelect
export type NewUser = typeof user.$inferInsert

export const account = sqliteTable(
  'account',
  {
    id: text('id').primaryKey(),
    accountId: text('accountId').notNull(),
    providerId: text('providerId').notNull(),
    userId: text('userId').notNull(),
    accessToken: text('accessToken'),
    refreshToken: text('refreshToken'),
    idToken: text('idToken'),
    accessTokenExpiresAt: integer('accessTokenExpiresAt'),
    refreshTokenExpiresAt: integer('refreshTokenExpiresAt'),
    scope: text('scope'),
    password: text('password'),
    createdAt: integer('createdAt').notNull(),
    updatedAt: integer('updatedAt').notNull(),
  },
)

export type Account = typeof account.$inferSelect
export type NewAccount = typeof account.$inferInsert

export const session = sqliteTable(
  'session',
  {
    id: text('id').primaryKey(),
    expiresAt: integer('expiresAt').notNull(),
    token: text('token').notNull().unique(),
    createdAt: integer('createdAt').notNull(),
    updatedAt: integer('updatedAt').notNull(),
    ipAddress: text('ipAddress'),
    userAgent: text('userAgent'),
    userId: text('userId').notNull(),
  },
)

export type AuthSession = typeof session.$inferSelect
export type NewAuthSession = typeof session.$inferInsert

export const verification = sqliteTable('verification', {
  id: text('id').primaryKey(),
  identifier: text('identifier').notNull(),
  value: text('value').notNull(),
  expiresAt: integer('expiresAt').notNull(),
  createdAt: integer('createdAt'),
  updatedAt: integer('updatedAt'),
})

export type Verification = typeof verification.$inferSelect
export type NewVerification = typeof verification.$inferInsert
