import { and, eq, isNull, ne, or } from 'drizzle-orm'
import { env } from '../config.js'
import { db } from '../db/client.js'
import { users } from '../db/schema.js'
import { hashPassword } from './password.js'

export async function ensureAdminAccount() {
  const loginId = env.ADMIN_ACCOUNT_ID.trim()
  const email = env.ADMIN_ACCOUNT_EMAIL.trim().toLowerCase()
  const nickname = env.ADMIN_ACCOUNT_NICKNAME.trim()
  const password = env.ADMIN_ACCOUNT_PASSWORD

  const now = new Date()

  await db
    .update(users)
    .set({
      role: 'user',
      updatedAt: now,
    })
    .where(
      and(
        eq(users.role, 'admin'),
        or(
          ne(users.loginId, loginId),
          isNull(users.loginId),
        ),
      ),
    )

  const [existingAdmin] = await db
    .select()
    .from(users)
    .where(
      or(
        eq(users.loginId, loginId),
        eq(users.email, email),
      ),
    )
    .limit(1)

  if (existingAdmin) {
    await db
      .update(users)
      .set({
        email,
        nickname,
        role: 'admin',
        updatedAt: now,
      })
      .where(eq(users.id, existingAdmin.id))

    return
  }

  const passwordHash = await hashPassword(password)

  await db.insert(users).values({
    email,
    loginId,
    passwordHash,
    nickname,
    role: 'admin',
    emailVerifiedAt: now,
    lastLoginAt: null,
    createdAt: now,
    updatedAt: now,
  })
}
