import { getDb } from '../client'
import { account } from '../schema'
import { eq, and } from 'drizzle-orm'

/** Account Repository（Better-Auth account 表，驼峰字段名）。 */

export const accountRepo = {
  /** 按 provider + accountId 查（唯一索引） */
  findByProviderAndAccountId(providerId: string, accountId: string) {
    return getDb()
      .select()
      .from(account)
      .where(and(eq(account.providerId, providerId), eq(account.accountId, accountId)))
      .get()
  },

  /** 按 userId 查所有关联账户 */
  listByUser(userId: string) {
    return getDb().select().from(account).where(eq(account.userId, userId)).all()
  },

  /** 按 userId + provider 查 */
  findByUserAndProvider(userId: string, providerId: string) {
    return getDb()
      .select()
      .from(account)
      .where(and(eq(account.userId, userId), eq(account.providerId, providerId)))
      .get()
  },

  /** 创建 */
  create(data: typeof account.$inferInsert) {
    getDb().insert(account).values(data).run()
  },

  /** 更新 */
  updateFields(id: string, fields: Partial<typeof account.$inferInsert>) {
    getDb().update(account).set(fields).where(eq(account.id, id)).run()
  },

  /** 按 userId 删除（用户删除级联用） */
  deleteByUser(userId: string) {
    getDb().delete(account).where(eq(account.userId, userId)).run()
  },
}
