/**
 * Optional self-setup at boot, for hosts where you have no shell.
 *
 *   AUTO_MIGRATE=true          applies schema.sql (idempotent)
 *   SEED_ADMIN_EMAIL/PASSWORD  creates or updates one admin account
 *
 * The admin seed exists so a deployment never has to ship a known default
 * login: you supply the password as a platform secret, and it is applied on
 * the next boot. Re-running is safe - the password is simply re-hashed.
 */
import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { env } from '../config/env.js';
import { pool } from './pool.js';
import { hashPassword } from '../auth/password.js';
import { logger } from '../utils/logger.js';

const here = dirname(fileURLToPath(import.meta.url));

export async function autoMigrate(): Promise<void> {
  if (!env.AUTO_MIGRATE) return;
  const sql = await readFile(join(here, 'schema.sql'), 'utf8');
  await pool.query(sql);
  logger.info('AUTO_MIGRATE: schema applied');
}

export async function seedAdmin(): Promise<void> {
  const email = env.SEED_ADMIN_EMAIL?.trim().toLowerCase();
  const password = env.SEED_ADMIN_PASSWORD;
  if (!email || !password) return;

  const hash = await hashPassword(password);
  const { rows } = await pool.query(
    `INSERT INTO agents (email, password_hash, name, role, max_concurrent_chats)
     VALUES ($1, $2, $3, 'admin', 8)
     ON CONFLICT (email) DO UPDATE
       SET password_hash = EXCLUDED.password_hash,
           name          = EXCLUDED.name,
           role          = 'admin'
     RETURNING id, (xmax = 0) AS created`,
    [email, hash, env.SEED_ADMIN_NAME],
  );
  // Never log the password itself.
  logger.info(`admin account ${rows[0]?.created ? 'created' : 'updated'}`, { email });
}
