/**
 * Dev helper: create a dev IAM user + an ACTIVE session, and print a ready-to-use Bearer token.
 *
 * Why this exists: in prod the central IAM service issues tokens (via password login at
 * /v1/auth/login). For local dev of the passenger API (a token *consumer*), this seeds a session
 * directly and mints a matching token with the package's own `generateToken`, so you can call
 * protected routes immediately (paste the token into Swagger's Authorize box or `curl -H`).
 *
 * Run:  pnpm --filter @edr/passenger-api iam:seed-dev-user
 * Reads DATABASE_* + JWT_ACCESS_TOKEN_SECRET/EXPIRES from .env (loaded via `node --env-file`).
 */
const crypto = require('crypto');
const { DataSource } = require('typeorm');
const { generateToken } = require('@tria-plc/api-common/utils/token');

const DEV_EMAIL = process.env.DEV_IAM_EMAIL || 'dev@edr.local';

const ds = new DataSource({
  type: 'postgres',
  host: process.env.DATABASE_HOST,
  port: Number(process.env.DATABASE_PORT || 5432),
  database: process.env.DATABASE_NAME,
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
});

(async () => {
  await ds.initialize();

  // Upsert the dev user (users.email is UNIQUE).
  const name = { en: 'Dev User', am: 'የሙከራ ተጠቃሚ' };
  const [user] = await ds.query(
    `INSERT INTO iam.users (name, username, email, user_type, status, is_active)
       VALUES ($1::jsonb, $2, $3, 'individual', 'accepted', true)
     ON CONFLICT (email) DO UPDATE SET updated_at = now()
     RETURNING id`,
    [JSON.stringify(name), 'dev-user', DEV_EMAIL],
  );
  const userId = user.id;

  // Fresh ACTIVE session; userInfo is the denormalized TCurrentUser the guard puts on req.user.
  const sessionId = crypto.randomUUID();
  const userInfo = {
    id: userId,
    email: DEV_EMAIL,
    name,
    username: 'dev-user',
    userType: 'individual',
    status: 'accepted',
    roles: [],
    permissions: [],
  };
  await ds.query(
    `INSERT INTO iam.sessions (id, email, device, "userInfo", user_id, status, expiry_time)
       VALUES ($1, $2, 'dev-seeder', $3::jsonb, $4, 'ACTIVE', now() + interval '7 days')`,
    [sessionId, DEV_EMAIL, JSON.stringify(userInfo), userId],
  );

  // The package JwtGuard looks up the session by the token's `id` claim.
  const token = generateToken({ id: sessionId });

  console.log('\n=== IAM dev user seeded ===');
  console.log('user id   :', userId);
  console.log('email     :', DEV_EMAIL);
  console.log('session id:', sessionId);
  console.log('\nBearer token (valid 7 days):\n' + token);
  console.log('\nTry it:  curl -H "Authorization: Bearer <token>" http://localhost:3002/v1/auth/me');
  console.log('(Run again any time for a fresh token/session.)\n');

  await ds.destroy();
})().catch((e) => {
  console.error('[seed-iam-dev-user] FAIL:', e.message);
  process.exit(1);
});
