/* Reset admin password for thallaa@gmail.com to a known value.
   Usage: node scripts/reset-admin-password.js
*/
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '..', '.env') });
const { PrismaClient, Role, UserStatus } = require('@prisma/client');
const { PrismaPg } = require('@prisma/adapter-pg');
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');

async function main() {
  const email = process.env.ADMIN_EMAIL || 'thallaa@gmail.com';
  const newPassword = process.env.ADMIN_INITIAL_PASSWORD;
  if (!newPassword) throw new Error('ADMIN_INITIAL_PASSWORD not set in env');
  if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL not set');

  const prisma = new PrismaClient({
    adapter: new PrismaPg(new Pool({ connectionString: process.env.DATABASE_URL })),
  });

  const hash = await bcrypt.hash(newPassword, 12);
  const user = await prisma.user.upsert({
    where: { email },
    update: {
      passwordHash: hash,
      role: Role.ADMIN,
      status: UserStatus.ACTIVE,
      emailVerifiedAt: new Date(),
      approvedAt: new Date(),
    },
    create: {
      email,
      passwordHash: hash,
      role: Role.ADMIN,
      status: UserStatus.ACTIVE,
      emailVerifiedAt: new Date(),
      approvedAt: new Date(),
    },
  });

  console.log('Password reset for', user.email);
  await prisma.$disconnect();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
