/**
 * Functional smoke for session renewal.
 *
 * The access token lives 15 minutes and there was no way to renew it: both SPAs
 * loaded the user once at mount and never revalidated, and no client had any
 * handling for UNAUTHORIZED. After fifteen minutes the shell stayed fully
 * rendered while every action failed, with a manual reload as the only way out.
 * That hits every user, every session, on day one.
 *
 * Asserts the server half: a refresh token is issued, exchanges for a working
 * access token, rotates, and is refused in every way it should be. The two
 * secrets are required to differ (config/env.ts), so the separation asserted in
 * C is enforced rather than assumed.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/auth-refresh-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { AuthService } from '../src/auth/auth.service';
import { hashPassword } from '../src/auth/password';
import { PrismaService } from '../src/prisma/prisma.service';

const prisma = new PrismaService();
const config = new ConfigService({
  JWT_ACCESS_SECRET: process.env.JWT_ACCESS_SECRET ?? 'dev-access-secret',
  JWT_REFRESH_SECRET: process.env.JWT_REFRESH_SECRET ?? 'dev-refresh-secret',
  JWT_ACCESS_TTL: process.env.JWT_ACCESS_TTL ?? '15m',
  JWT_REFRESH_TTL: process.env.JWT_REFRESH_TTL ?? '30d',
});
const jwt = new JwtService({
  secret: config.get<string>('JWT_ACCESS_SECRET'),
  signOptions: { expiresIn: config.get<string>('JWT_ACCESS_TTL') as `${number}m` },
});
const auth = new AuthService(prisma, jwt, config);

let pass = 0, fail = 0;
const ck = (n: string, c: boolean, d = '') => { c ? (pass++, console.log(`  ✓ ${n}`)) : (fail++, console.log(`  ✗ ${n}  ${d}`)); };

const EMAIL = 'zz-refresh-smoke@rms.local';
const PASSWORD = 'zz-Refresh-Smoke-1';

/** The `exp` claim, read without verifying — this is a test, not a gate. */
function expOf(token: string): number {
  return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()).exp as number;
}

/** Runs fn and returns the error message, or '' when it did not throw. */
async function refused(fn: () => Promise<unknown>): Promise<string> {
  try {
    await fn();
    return '';
  } catch (e) {
    return e instanceof Error ? e.message : String(e);
  }
}

async function main() {
  const role = await prisma.role.findFirst({ where: { code: 'STAFF' }, select: { id: true } });
  if (!role) throw new Error('no STAFF role');

  await purgeStale();
  const user = await prisma.user.create({
    data: {
      email: EMAIL, name: 'ZZ Refresh Smoke',
      passwordHash: hashPassword(PASSWORD), isActive: true,
      roles: { create: [{ roleId: role.id }] },
    },
  });

  console.log('A. Logging in hands back both tokens');
  const session = await auth.login(EMAIL, PASSWORD);
  ck('A1 an access token', typeof session.accessToken === 'string' && session.accessToken.length > 20);
  ck('A2 and a refresh token', typeof session.refreshToken === 'string' && session.refreshToken.length > 20);
  ck('A3 they are not the same token', session.accessToken !== session.refreshToken);
  ck('A4 the access token identifies the user', (await auth.verifyAndLoad(session.accessToken))?.id === user.id);

  console.log('');
  console.log('B. The refresh token buys a new session');
  const renewed = await auth.refresh(session.refreshToken);
  ck('B1 a fresh access token comes back', typeof renewed.accessToken === 'string');
  ck('B2 which works', (await auth.verifyAndLoad(renewed.accessToken))?.id === user.id);
  ck('B3 a refresh token comes back with it', renewed.refreshToken.length > 20);
  ck('B4 and that one works too', (await auth.refresh(renewed.refreshToken)).accessToken.length > 20);
  // The point of re-issuing is the sliding window: a session that keeps being
  // used keeps moving its own deadline, so it never dies under an active user.
  // (Two JWTs signed in the same second are byte-identical, hence the wait —
  // asserting the strings differ would have tested the clock, not the window.)
  const firstExp = expOf(session.refreshToken);
  await new Promise((r) => setTimeout(r, 1100));
  const later = await auth.refresh(session.refreshToken);
  ck('B4b using it pushes the expiry further out', expOf(later.refreshToken) > firstExp, `${expOf(later.refreshToken)} vs ${firstExp}`);
  ck('B5 permissions come back with it, so a role change lands', renewed.user.permissions.length > 0);

  console.log('');
  console.log('C. The two token kinds cannot stand in for each other');
  // The whole point of a separate secret: an access token must not renew a
  // session, and a refresh token must not authorise a call.
  const asRefresh = await refused(() => auth.refresh(session.accessToken));
  ck('C1 an access token is not accepted as a refresh token', asRefresh !== '', 'a 15-minute token would become a 30-day one');
  ck('C2 a refresh token does not authenticate a call', (await auth.verifyAndLoad(session.refreshToken)) === null);

  console.log('');
  console.log('D. Renewal is refused when it should be');
  ck('D1 garbage is refused', (await refused(() => auth.refresh('not-a-token'))) !== '');
  ck('D2 an empty string is refused', (await refused(() => auth.refresh(''))) !== '');
  // Signed with the right secret and shape but never issued by us.
  const forged = await new JwtService({ secret: 'some-other-secret' }).signAsync({ sub: user.id, typ: 'refresh' });
  ck('D3 a token signed with another secret is refused', (await refused(() => auth.refresh(forged))) !== '');

  console.log('');
  console.log('E. Deactivating the account ends the session at the next renewal');
  const still = await auth.refresh(renewed.refreshToken);
  ck('E1 renewal works while the account is active', still.accessToken.length > 20);
  await prisma.user.update({ where: { id: user.id }, data: { isActive: false } });
  const afterDisable = await refused(() => auth.refresh(still.refreshToken));
  ck('E2 and stops the moment it is deactivated', afterDisable !== '', 'a disabled account could renew indefinitely');
  ck('E3 the already-issued access token stops working too', (await auth.verifyAndLoad(still.accessToken)) === null);
}

async function purgeStale() {
  const users = await prisma.user.findMany({ where: { email: EMAIL }, select: { id: true } });
  const ids = users.map((u) => u.id);
  if (!ids.length) return;
  await prisma.userRole.deleteMany({ where: { userId: { in: ids } } });
  await prisma.user.deleteMany({ where: { id: { in: ids } } });
}

async function cleanup() {
  try { await purgeStale(); console.log('\nCleanup: OK'); }
  catch (e) { console.log(`\nCleanup WARNING: ${e instanceof Error ? e.message : e}`); }
}

main().catch((e) => { fail++; console.log(`\nFATAL: ${e instanceof Error ? e.stack : e}`); }).finally(async () => { await cleanup(); await prisma.$disconnect(); console.log(`\n==== ${pass} passed, ${fail} failed ====`); process.exit(fail > 0 ? 1 : 0); });
