// src/db/seed_admin_account.ts
import { Pool } from 'pg';
import bcrypt from 'bcrypt';

const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  password: process.env.DB_PASSWORD,
  port: parseInt(process.env.DB_PORT || '5432', 10), // Keep fallback for port
});

const ADMIN_EMAIL = 'admin@example.com';
const ADMIN_PASSWORD = 'adminpass'; // The plain text password for development/testing

async function seedAdminUser() {
  const client = await pool.connect();
  console.log('Connected to the database.');

  try {
    // Check if the admin user already exists
    const existingUserRes = await client.query('SELECT user_id FROM public.users WHERE email = $1', [ADMIN_EMAIL]);

    if (existingUserRes.rows.length > 0) {
      const userId = existingUserRes.rows[0].user_id;
      console.log(`Admin user '${ADMIN_EMAIL}' already exists with ID: ${userId}.`);

      // Ensure the user has the 'admin' role
      const profileRes = await client.query("SELECT role FROM public.profiles WHERE user_id = $1", [userId]);
      if (profileRes.rows.length === 0 || profileRes.rows[0].role !== 'admin') {
        await client.query("UPDATE public.profiles SET role = 'admin' WHERE id = $1", [userId]);
        console.log(`Updated role to 'admin' for user ${userId}.`);
      } else {
        console.log(`User ${userId} already has 'admin' role.`);
      }
      return;
    }

    // If user does not exist, create them
    console.log(`Admin user '${ADMIN_EMAIL}' not found. Creating...`);
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(ADMIN_PASSWORD, saltRounds);

    // Insert into the users table. The `handle_new_user` trigger will create the profile.
    const newUserRes = await client.query(
      'INSERT INTO public.users (email, password_hash) VALUES ($1, $2) RETURNING user_id',
      [ADMIN_EMAIL, hashedPassword]
    );

    const newUserId = newUserRes.rows[0].user_id;
    console.log(`Successfully created user with ID: ${newUserId}.`);

    // The trigger creates a profile with the 'user' role. We now update it to 'admin'.
    await client.query(
      "UPDATE public.profiles SET role = 'admin' WHERE user_id = $1",
      [newUserId]
    );

    console.log(`Successfully set role to 'admin' for user ${newUserId}.`);
    console.log('Admin user seeding complete!');

  } catch (error) {
    console.error('Error during admin user seeding:', error);
  } finally {
    await client.release();
    console.log('Database client released.');
    await pool.end();
    console.log('Connection pool closed.');
  }
}

// Execute the seeding function
seedAdminUser();