import { getDb } from '../client'
import { authSession } from '../schema'
import { eq, lt } from 'drizzle-orm'

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

export const authSessionRepo = {
  /** 按 token 查（登录验证用） */
  findByToken(token: string) {
    return getDb().select().from(authSession).where(eq(authSession.token, token)).get()
  },

  /** 按 id 查 */
  findById(id: string) {
    return getDb().select().from(authSession).where(eq(authSession.id, id)).get()
  },

  /** 按 userId 查所有会话 */
  listByUser(userId: string) {
    return getDb().select().from(authSession).where(eq(authSession.userId, userId)).all()
  },

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

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

  /** 按 token 删除（登出用） */
  deleteByToken(token: string) {
    getDb().delete(authSession).where(eq(authSession.token, token)).run()
  },

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

  /** 删除过期会话（nowMs = Date.now()） */
  deleteExpired(nowMs: number) {
    getDb().delete(authSession).where(lt(authSession.expiresAt, nowMs)).run()
  },
}
