import { eq } from "drizzle-orm"

import { auth } from "@/lib/auth"
import { db, sql } from "@/lib/db/client"
import { account, user } from "@/lib/db/auth-schema"
import { people } from "@/lib/db/schema"

/**
 * Set somebody's password, knowing only their employee code.
 *
 * This is the reset that ELEVA-134 describes: there is no mail in this
 * building, so a forgotten password is set by Admin or HR and handed over in
 * person. The person is identified by the eight digits on their card.
 *
 *     bun run db:password 00001201 admin1
 *
 * It hashes through Better Auth's own hasher rather than reaching for a
 * library, so the stored value is exactly what a sign-in will be checked
 * against. Nothing here re-implements a credential.
 */

const code = process.argv[2]
const secret = process.argv[3]

if (!code || !secret) {
  console.error("Usage: bun run db:password <employee code> <new password>")
  process.exit(1)
}

const [person] = await db
  .select({ authUserId: people.authUserId, first: people.firstName })
  .from(people)
  .where(eq(people.employeeCode, code))

if (!person) {
  console.error(`No employee code ${code} in the roster.`)
  await sql.end()
  process.exit(1)
}
if (!person.authUserId) {
  console.error(`${code} has no login yet. Run: bun run db:provision ${code}`)
  await sql.end()
  process.exit(1)
}

const context = await auth.$context
const hash = await context.password.hash(secret)

// The credential row, not the user: Better Auth keeps the hash on the
// `credential` provider account, which is the row a username sign-in checks.
const updated = await db
  .update(account)
  .set({ password: hash })
  .where(eq(account.userId, person.authUserId))
  .returning({ id: account.id })

if (updated.length === 0) {
  console.error(`${code} has a user but no credential row. Provision it again.`)
  await sql.end()
  process.exit(1)
}

const [who] = await db
  .select({ name: user.name, username: user.username })
  .from(user)
  .where(eq(user.id, person.authUserId))

console.log(`${who?.username}  ${who?.name}`)
console.log(`password set to: ${secret}`)

await sql.end()
