import { eq } from 'drizzle-orm';
import { authUsers, customAuthSchema } from '@platform-modules/auth/engine-custom';
import { createNeonHttpClient } from '@platform-modules/db/neon-http';
import { buildAuthEngine, type AdminEnv } from '../src/lib/admin-engine.js';

// Seeds the initial admin USER (idempotent) so a human can sign in to the admin
// dashboard and the Task-6 e2e login path has a real account.
//
// NOTE — the agent/MCP bearer credential is NOT issued here, by design. It is now
// a first-class opaque service token (PAT) minted by a separate script,
// scripts/issue-service-token.ts, so its raw value is printed once and never
// co-mingled with user seeding. The Bearer path in src/lib/auth.ts accepts it via
// resolveServiceToken (engine-custom). See
// docs/specs/2026-06-12-auth-util-module-boundaries.md service-token section.

type SeedEnv = Omit<AdminEnv, 'DATABASE_URL' | 'DB'> & {
  DATABASE_URL: string;
  SEED_ADMIN_EMAIL: string;
  SEED_ADMIN_PASSWORD: string;
};

const REQUIRED_ENV_KEYS = [
  'DATABASE_URL',
  'AUTH_PEPPER',
  'AUTH_SESSION_SECRET',
  'SEED_ADMIN_EMAIL',
  'SEED_ADMIN_PASSWORD',
] as const;

function parseEnv(): SeedEnv {
  const missing = REQUIRED_ENV_KEYS.filter((key) => !process.env[key]?.trim());
  if (missing.length > 0) {
    throw new Error(
      `seed-admin: missing required environment variable(s): ${missing.join(', ')}`,
    );
  }

  return {
    DATABASE_URL: process.env.DATABASE_URL!,
    AUTH_PEPPER: process.env.AUTH_PEPPER!,
    AUTH_SESSION_SECRET: process.env.AUTH_SESSION_SECRET!,
    SEED_ADMIN_EMAIL: process.env.SEED_ADMIN_EMAIL!,
    SEED_ADMIN_PASSWORD: process.env.SEED_ADMIN_PASSWORD!,
  };
}

async function findUserByEmail(env: SeedEnv, email: string) {
  const db = createNeonHttpClient({
    connectionString: env.DATABASE_URL,
    schema: customAuthSchema,
  });
  const [row] = await db
    .select({ id: authUsers.id })
    .from(authUsers)
    .where(eq(authUsers.email, email.toLowerCase()))
    .limit(1);
  return row ?? null;
}

async function main(): Promise<void> {
  const env = parseEnv();
  const engine = buildAuthEngine(env);

  const existing = await findUserByEmail(env, env.SEED_ADMIN_EMAIL);
  if (existing) {
    console.log('admin user already present');
    return;
  }

  await engine.createUser({
    email: env.SEED_ADMIN_EMAIL,
    password: env.SEED_ADMIN_PASSWORD,
    roles: ['admin'],
  });
  console.log('admin user seeded');
}

main().catch((err: unknown) => {
  const message = err instanceof Error ? err.message : String(err);
  console.error(`seed-admin failed: ${message}`);
  process.exitCode = 1;
});
