const fs = require('node:fs');
const path = require('node:path');
const bcrypt = require('bcryptjs');
const postgres = require('postgres');

function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) {
    return;
  }

  const content = fs.readFileSync(filePath, 'utf8');

  for (const rawLine of content.split(/\r?\n/)) {
    const line = rawLine.trim();

    if (!line || line.startsWith('#')) {
      continue;
    }

    const separatorIndex = line.indexOf('=');

    if (separatorIndex === -1) {
      continue;
    }

    const key = line.slice(0, separatorIndex).trim();
    let value = line.slice(separatorIndex + 1).trim();

    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1);
    }

    if (!(key in process.env)) {
      process.env[key] = value;
    }
  }
}

function loadLocalEnv() {
  loadEnvFile(path.resolve(process.cwd(), '.env.local'));
  loadEnvFile(path.resolve(process.cwd(), '.env'));
}

function requireEnv(name) {
  const value = process.env[name]?.trim();

  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }

  return value;
}

async function main() {
  loadLocalEnv();

  const databaseUrl = requireEnv('DATABASE_URL');
  const email = requireEnv('SUPER_ADMIN_EMAIL').toLowerCase();
  const password = requireEnv('SUPER_ADMIN_PASSWORD');
  const name = process.env.SUPER_ADMIN_NAME?.trim() || 'Super Admin';
  const resetPassword = process.env.SUPER_ADMIN_RESET_PASSWORD === 'true';

  if (password.length < 8) {
    throw new Error('SUPER_ADMIN_PASSWORD must be at least 8 characters long');
  }

  const sql = postgres(databaseUrl, { prepare: false });

  try {
    const existingUsers = await sql`
      select id, system_role
      from users
      where email = ${email}
      limit 1
    `;

    const passwordHash = await bcrypt.hash(password, 10);

    if (existingUsers.length === 0) {
      const id = crypto.randomUUID();

      await sql`
        insert into users (
          id,
          name,
          email,
          password_hash,
          system_role,
          active_organization_id
        ) values (
          ${id},
          ${name},
          ${email},
          ${passwordHash},
          ${'super_admin'},
          ${null}
        )
      `;

      console.log(`Created super admin user: ${email}`);
      return;
    }

    const user = existingUsers[0];

    if (resetPassword) {
      await sql`
        update users
        set
          name = ${name},
          system_role = ${'super_admin'},
          password_hash = ${passwordHash},
          updated_at = now()
        where id = ${user.id}
      `;

      console.log(`Promoted and reset password for super admin user: ${email}`);
      return;
    }

    await sql`
      update users
      set
        name = ${name},
        system_role = ${'super_admin'},
        updated_at = now()
      where id = ${user.id}
    `;

    console.log(`Ensured super admin role for user: ${email}`);
  } finally {
    await sql.end();
  }
}

main().catch((error) => {
  console.error('[seed-super-admin] Failed:', error.message);
  process.exitCode = 1;
});
