/**
 * Functional smoke: the user manual inside the back office.
 *
 * The manual existed only as docs/user-manual.html in the repo — staff had to be
 * shown where the file was, and the obvious fix (drop it next to the SPA's
 * index.html) would have published it: its screenshots show the twenty real
 * landlord companies and their accounting codes. So it is served from an
 * authenticated route instead, and what that route lets through is the whole
 * point of this smoke.
 *
 * Against a real HTTP server with the real router and the real 5 MB file:
 *   · a full staff login gets the document, as HTML, with the headers a private
 *     document should carry;
 *   · a read-only staff login gets exactly the same bytes — no permission key
 *     gates documentation;
 *   · a TENANT login is refused: this is the back-office manual;
 *   · a staff login that still owes a password change is refused too — the same
 *     two lines staffProcedure draws, drawn here as well, because a password
 *     somebody else chose and read out over the phone should not pull a document
 *     that names every landlord company;
 *   · anonymous, a garbage token and a token signed with the wrong secret are
 *     all refused identically, so none of them tells the caller anything;
 *   · when the file was never deployed the operator gets a sentence saying so
 *     and not a stack trace — and every refusal above reads exactly the same as
 *     it does when the file IS there, so a refused caller cannot learn whether
 *     the server has a manual at all.
 *
 * Standalone, self-cleaning: its own ZZ organisation, role and logins, purged at
 * both ends.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/manual-smoke.ts
 */
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import express from 'express';
import { createServer } from 'node:http';
import { statSync } from 'node:fs';
import { join } from 'node:path';
import type { AddressInfo } from 'node:net';
import { AuthService } from '../src/auth/auth.service';
import { hashPassword } from '../src/auth/password';
import { createManualRouter } from '../src/manual/manual.adapter';
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 PFX = 'ZZ-MAN';
const ORG_CODE = `${PFX}-ORG`;
const ROLE_CODE = `${PFX}-READONLY`;
const ADMIN_EMAIL = 'zz-manual-admin@rms.local';
const READONLY_EMAIL = 'zz-manual-readonly@rms.local';
const TENANT_EMAIL = 'zz-manual-tenant@rms.local';
const FORCED_EMAIL = 'zz-manual-forced@rms.local';
const PASSWORD = 'zz-Manual-Smoke-1';

/** The real file the build ships — the same one the router resolves. */
const MANUAL = join(__dirname, '..', '..', '..', 'docs', 'user-manual.html');
/** A path that is certainly not there, so "never deployed" can be exercised. */
const ABSENT = join(__dirname, 'zz-no-such-user-manual.html');

interface Reply { status: number; type: string; body: string; headers: Headers }

async function purge() {
  await prisma.user.deleteMany({ where: { email: { in: [ADMIN_EMAIL, READONLY_EMAIL, TENANT_EMAIL, FORCED_EMAIL] } } });
  const org = await prisma.organization.findUnique({ where: { code: ORG_CODE }, select: { id: true } });
  if (org) {
    await prisma.tenant.deleteMany({ where: { organizationId: org.id } });
    await prisma.organization.delete({ where: { id: org.id } });
  }
  await prisma.role.deleteMany({ where: { code: ROLE_CODE } });
}

async function main() {
  await purge();

  // Two mounts on one server: the same router, once over the real file and once
  // over a path that does not exist. That is what makes "the refusal is the
  // same either way" checkable rather than argued.
  const app = express();
  app.use('/api/manual', createManualRouter(auth));
  app.use('/undeployed', createManualRouter(auth, [ABSENT]));
  const server = createServer(app);
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  const port = (server.address() as AddressInfo).port;

  const get = async (path: string, token?: string): Promise<Reply> => {
    const res = await fetch(`http://127.0.0.1:${port}${path}`, {
      headers: token === undefined ? {} : { Authorization: `Bearer ${token}` },
    });
    return { status: res.status, type: res.headers.get('content-type') ?? '', body: await res.text(), headers: res.headers };
  };

  const org = await prisma.organization.create({ data: { code: ORG_CODE, name: 'Manual smoke org' } });
  const adminRole = await prisma.role.findFirstOrThrow({ where: { code: 'ADMIN' }, select: { id: true } });
  // A genuine read-only role: every `.read` there is and nothing else.
  const reads = await prisma.permission.findMany({ where: { key: { endsWith: '.read' } }, select: { id: true } });
  const readOnlyRole = await prisma.role.create({
    data: { code: ROLE_CODE, name: 'ZZ Read only', permissions: { create: reads.map((p) => ({ permissionId: p.id })) } },
  });
  const tenant = await prisma.tenant.create({ data: { organizationId: org.id, name: `${PFX} Tenant` } });
  const mk = (email: string, name: string, roleId: string, tenantId: string | null, mustChangePassword = false) =>
    prisma.user.create({
      data: { email, name, passwordHash: hashPassword(PASSWORD), isActive: true, tenantId, mustChangePassword, roles: { create: [{ roleId }] } },
    });
  await mk(ADMIN_EMAIL, 'ZZ Manual Admin', adminRole.id, null);
  await mk(READONLY_EMAIL, 'ZZ Manual Read-only', readOnlyRole.id, null);
  // A full admin whose password the office reset for them and who has not yet
  // replaced it — the state DEPLOY.md's recovery flow leaves an account in.
  await mk(FORCED_EMAIL, 'ZZ Manual Forced', adminRole.id, null, true);
  const tenantRole = await prisma.role.findFirstOrThrow({ where: { code: 'TENANT' }, select: { id: true } });
  await mk(TENANT_EMAIL, 'ZZ Manual Tenant', tenantRole.id, tenant.id);

  const adminToken = (await auth.login(ADMIN_EMAIL, PASSWORD)).accessToken;
  const readOnlyToken = (await auth.login(READONLY_EMAIL, PASSWORD)).accessToken;
  const tenantToken = (await auth.login(TENANT_EMAIL, PASSWORD)).accessToken;
  const forcedToken = (await auth.login(FORCED_EMAIL, PASSWORD)).accessToken;
  // Correctly formed, correctly signed — with the wrong key. The shape of the
  // token must not be what decides; the signature must.
  const wrongSecret = await new JwtService({ secret: 'zz-not-the-access-secret' }).signAsync({ sub: 'whoever' });

  console.log('A. A staff login gets the manual');
  const asAdmin = await get('/api/manual', adminToken);
  ck('A1 200', asAdmin.status === 200, String(asAdmin.status));
  ck('A2 served as HTML', asAdmin.type === 'text/html; charset=utf-8', asAdmin.type);
  // Newlines normalized: the file is generated and checked in without
  // .gitattributes protection for long enough that clones made before it exist
  // with CRLF, and which newline the office's checkout happens to have says
  // nothing about whether the route works.
  ck('A3 it is the manual, from its first bytes', asAdmin.body.replace(/\r\n/g, '\n').startsWith('<!doctype html>\n<html lang="zh-Hant">'), JSON.stringify(asAdmin.body.slice(0, 60)));
  ck('A4 the whole document, not a truncated one', asAdmin.body.length > 3_000_000 && asAdmin.body.trimEnd().endsWith('</html>'), String(asAdmin.body.length));
  ck('A5 byte-for-byte the file the build ships', Buffer.byteLength(asAdmin.body) === statSync(MANUAL).size, `${Buffer.byteLength(asAdmin.body)} vs ${statSync(MANUAL).size}`);
  ck('A6 its table of contents came with it', asAdmin.body.includes('href="#billing"') && asAdmin.body.includes('id="billing"'));
  ck('A7 not cached anywhere on the way', asAdmin.headers.get('cache-control') === 'private, no-store', asAdmin.headers.get('cache-control') ?? '');
  ck('A8 and not sniffable into something else', asAdmin.headers.get('x-content-type-options') === 'nosniff');

  console.log('\nB. So does a read-only staff login — documentation is not data');
  const asReadOnly = await get('/api/manual', readOnlyToken);
  ck('B1 200', asReadOnly.status === 200, String(asReadOnly.status));
  ck('B2 the same document', asReadOnly.body.length === asAdmin.body.length);

  console.log('\nC. Everyone else is refused');
  const asTenant = await get('/api/manual', tenantToken);
  ck('C1 a tenant login is refused', asTenant.status === 403, String(asTenant.status));
  ck('C2 and told why', JSON.parse(asTenant.body).error === 'This is a tenant account and cannot use the back office', asTenant.body);
  // A password the office typed and read out to its holder is not yet a
  // credential only that person has, so it does not open the manual either —
  // the same refusal staffProcedure gives, and it costs a real user nothing,
  // since the admin shell shows the forced-password screen instead of a sidebar.
  const asForced = await get('/api/manual', forcedToken);
  ck('C3 a staff login still owing a password change is refused', asForced.status === 403, String(asForced.status));
  ck('C4 in staffProcedure\'s own words', JSON.parse(asForced.body).error === 'Change your password before continuing', asForced.body);
  const anon = await get('/api/manual');
  ck('C5 no token at all is refused', anon.status === 401 && JSON.parse(anon.body).error === 'Unauthorized', `${anon.status} ${anon.body}`);
  const garbage = await get('/api/manual', 'not-a-token');
  ck('C6 a garbage token reads exactly like no token', garbage.status === anon.status && garbage.body === anon.body, `${garbage.status} ${garbage.body}`);
  const forged = await get('/api/manual', wrongSecret);
  ck('C7 so does one signed with the wrong secret', forged.status === anon.status && forged.body === anon.body, `${forged.status} ${forged.body}`);
  ck('C8 none of them received any of the document', [asTenant, asForced, anon, garbage, forged].every((r) => !r.body.includes('<html')));

  console.log('\nD. A manual that was never deployed');
  const missing = await get('/undeployed', adminToken);
  ck('D1 the operator gets a 404', missing.status === 404, String(missing.status));
  ck('D2 saying what actually happened', JSON.parse(missing.body).error === 'The user manual was not deployed with this server', missing.body);
  ck('D3 and not a stack trace', !/\n\s+at |Error:/.test(missing.body), missing.body.slice(0, 120));

  console.log('\nE. …and the refusals do not change when it is missing');
  const gone = {
    tenant: await get('/undeployed', tenantToken),
    anon: await get('/undeployed'),
    garbage: await get('/undeployed', 'not-a-token'),
  };
  ck('E1 a tenant is refused identically', gone.tenant.status === asTenant.status && gone.tenant.body === asTenant.body, `${gone.tenant.status} ${gone.tenant.body}`);
  ck('E2 so is an anonymous caller', gone.anon.status === anon.status && gone.anon.body === anon.body, `${gone.anon.status} ${gone.anon.body}`);
  ck('E3 so is a garbage token', gone.garbage.status === garbage.status && gone.garbage.body === garbage.body, `${gone.garbage.status} ${gone.garbage.body}`);
  ck('E4 a refused caller learns nothing about whether a manual exists',
    new Set([asTenant.body, gone.tenant.body]).size === 1 && new Set([anon.body, gone.anon.body, garbage.body, gone.garbage.body]).size === 1);

  // A read-only login getting the manual is only meaningful if that login is
  // genuinely read-only — otherwise B says nothing.
  const readOnlyUser = await auth.verifyAndLoad(readOnlyToken);
  console.log('\nF. The read-only login really is read-only');
  ck('F1 it holds only reads', (readOnlyUser?.permissions ?? []).every((p) => p.endsWith('.read')) && (readOnlyUser?.permissions.length ?? 0) > 0,
    (readOnlyUser?.permissions ?? []).filter((p) => !p.endsWith('.read')).join(','));
  ck('F2 and is not a tenant account', readOnlyUser?.tenantId === null);

  await new Promise<void>((resolve) => server.close(() => resolve()));
}

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