/**
 * Functional smoke for changing your own password.
 *
 * Until now the only two writers of a password hash were users.create and
 * users.update, both behind role.update — an admin-level grant. So a tenant
 * handed credentials by the office could never change them, staff necessarily
 * knew every tenant's password because staff typed it, and a Leasing or
 * Accounting user could not rotate their own.
 *
 * Driven through the routers' own callers rather than prisma, because the point
 * of the feature is WHERE the procedure sits: on protectedProcedure, reachable
 * by any login, with no permission in front of it. Calling prisma directly
 * would assert nothing about that.
 *
 * Standalone, self-cleaning.
 * Run: cd apps/api && dotenv -e ../../.env -- ts-node -P tsconfig.json scripts/password-smoke.ts
 */
import 'reflect-metadata';
import { hashPassword, verifyPassword } from '../src/auth/password';
import { PrismaService } from '../src/prisma/prisma.service';
import { accountRouter } from '../src/trpc/routers/account.router';
import { usersRouter } from '../src/trpc/routers/users.router';
import type { AuthUser } from '../src/trpc/auth-user';
import type { Context } from '../src/trpc/trpc';

const prisma = new PrismaService();

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

const STAFF_EMAIL = 'zz-pw-staff@rms.local';
const TENANT_EMAIL = 'zz-pw-tenant@rms.local';
const ADMIN_EMAIL = 'zz-pw-admin@rms.local';
const TENANT_NAME = 'ZZ Pw Tenant';
const START = 'zz-Start-1';

function ctxFor(user: AuthUser, orgId: string): Context {
  return { prisma, user, organizationId: orgId, hashPassword, verifyPassword } as unknown as Context;
}
const account = (user: AuthUser, orgId: string) => accountRouter.createCaller(ctxFor(user, orgId));
const users = (user: AuthUser, orgId: string) => usersRouter.createCaller(ctxFor(user, orgId));

const hashOf = async (id: string) =>
  (await prisma.user.findUniqueOrThrow({ where: { id }, select: { passwordHash: true } })).passwordHash;
const mustChange = async (id: string) =>
  (await prisma.user.findUniqueOrThrow({ where: { id }, select: { mustChangePassword: true } })).mustChangePassword;

/** Runs fn and returns { message, code }, or empty strings if it did not throw. */
async function refused(fn: () => Promise<unknown>): Promise<{ message: string; code: string }> {
  try {
    await fn();
    return { message: '', code: '' };
  } catch (e) {
    const err = e as { message?: string; code?: string };
    return { message: err.message ?? String(e), code: err.code ?? '' };
  }
}

async function main() {
  const org = await prisma.organization.findFirst({ where: { deletedAt: null }, select: { id: true } });
  if (!org) throw new Error('no org');
  const orgId = org.id;
  const staffRole = await prisma.role.findFirst({ where: { code: 'STAFF' }, select: { id: true } });
  const adminRole = await prisma.role.findFirst({ where: { code: 'ADMIN' }, include: { permissions: { include: { permission: true } } } });
  if (!staffRole || !adminRole) throw new Error('roles missing');

  await purgeStale();

  const tenantParty = await prisma.tenant.create({ data: { organizationId: orgId, name: TENANT_NAME } });
  const staffUser = await prisma.user.create({
    data: { email: STAFF_EMAIL, name: 'ZZ Pw Staff', passwordHash: hashPassword(START), roles: { create: [{ roleId: staffRole.id }] } },
  });
  const tenantUser = await prisma.user.create({
    data: { email: TENANT_EMAIL, name: 'ZZ Pw Tenant Login', passwordHash: hashPassword(START), tenantId: tenantParty.id },
  });
  const adminUser = await prisma.user.create({
    data: { email: ADMIN_EMAIL, name: 'ZZ Pw Admin', passwordHash: hashPassword(START), roles: { create: [{ roleId: adminRole.id }] } },
  });

  const asStaff: AuthUser = { id: staffUser.id, email: STAFF_EMAIL, name: 'ZZ Pw Staff', tenantId: null, mustChangePassword: false, roles: ['STAFF'], permissions: [] };
  const asTenant: AuthUser = { id: tenantUser.id, email: TENANT_EMAIL, name: 'ZZ Pw Tenant Login', tenantId: tenantParty.id, mustChangePassword: false, roles: ['TENANT'], permissions: [] };
  const asAdmin: AuthUser = {
    id: adminUser.id, email: ADMIN_EMAIL, name: 'ZZ Pw Admin', tenantId: null, mustChangePassword: false, roles: ['ADMIN'],
    permissions: adminRole.permissions.map((p) => p.permission.key),
  };

  console.log('A. Anyone can change their own password, with no permission at all');
  ck('A1 the staff login holds no permission whatsoever', asStaff.permissions.length === 0);
  await account(asStaff, orgId).changePassword({ currentPassword: START, newPassword: 'zz-New-Staff-1' });
  const staffHash = await hashOf(staffUser.id);
  ck('A2 the old password no longer verifies', !verifyPassword(START, staffHash));
  ck('A3 and the new one does', verifyPassword('zz-New-Staff-1', staffHash));

  console.log('');
  console.log('B. A tenant login goes through the very same procedure');
  // If this ever moves onto staffProcedure, B2 goes red — and a tenant is back
  // to living with a password the office chose and still knows.
  await account(asTenant, orgId).changePassword({ currentPassword: START, newPassword: 'zz-New-Tenant-1' });
  const tenantHash = await hashOf(tenantUser.id);
  ck('B1 the tenant’s new password verifies', verifyPassword('zz-New-Tenant-1', tenantHash));
  ck('B2 and the old one does not', !verifyPassword(START, tenantHash));

  console.log('');
  console.log('C. A wrong current password changes nothing');
  const before = await hashOf(staffUser.id);
  const wrong = await refused(() => account(asStaff, orgId).changePassword({ currentPassword: 'not-it', newPassword: 'zz-Other-1' }));
  ck('C1 it is refused', wrong.message !== '');
  ck('C2 with that exact message', wrong.message === 'Current password is incorrect', `got "${wrong.message}"`);
  // A regression to UNAUTHORIZED signs the user out of both SPAs on a typo, and
  // looks exactly like an ordinary session expiry when tested by hand.
  ck('C3 as BAD_REQUEST, never UNAUTHORIZED', wrong.code === 'BAD_REQUEST', `got ${wrong.code}`);
  ck('C4 and the stored hash is byte-identical', (await hashOf(staffUser.id)) === before);

  console.log('');
  console.log('D. The weak and the pointless are refused too');
  const short = await refused(() => account(asStaff, orgId).changePassword({ currentPassword: 'zz-New-Staff-1', newPassword: 'zz-1' }));
  ck('D1 a five-character password is refused', short.message !== '');
  ck('D2 leaving the hash untouched', (await hashOf(staffUser.id)) === before);
  const same = await refused(() => account(asStaff, orgId).changePassword({ currentPassword: 'zz-New-Staff-1', newPassword: 'zz-New-Staff-1' }));
  ck('D3 reusing the current password is refused', same.message.includes('must be different'), `got "${same.message}"`);
  ck('D4 leaving the hash untouched', (await hashOf(staffUser.id)) === before);

  console.log('');
  console.log('E. A password somebody else typed is a one-time credential');
  const created = await users(asAdmin, orgId).create({ email: 'zz-pw-made@rms.local', name: 'ZZ Pw Made', password: 'zz-Made-1', roleIds: [staffRole.id] });
  ck('E1 a user an admin creates must change it', (await mustChange(created.id)) === true);
  const madeUser: AuthUser = { id: created.id, email: 'zz-pw-made@rms.local', name: 'ZZ Pw Made', tenantId: null, mustChangePassword: true, roles: ['STAFF'], permissions: [] };
  await account(madeUser, orgId).changePassword({ currentPassword: 'zz-Made-1', newPassword: 'zz-Made-New-1' });
  ck('E2 changing it clears the flag', (await mustChange(created.id)) === false);

  await users(asAdmin, orgId).update({ id: created.id, name: 'ZZ Pw Made', isActive: true, roleIds: [staffRole.id], newPassword: 'zz-Reset-1' });
  ck('E3 an admin resetting it re-arms the flag', (await mustChange(created.id)) === true);

  // Changing your OWN password through the users screen is not somebody else
  // choosing it, so it must not lock you out of your own back office.
  await users(asAdmin, orgId).update({ id: adminUser.id, name: 'ZZ Pw Admin', isActive: true, roleIds: [adminRole.id], newPassword: 'zz-Admin-New-1' });
  ck('E4 but changing your own does not', (await mustChange(adminUser.id)) === false, 'an admin would lock themselves out on every password change');
}

async function purgeStale() {
  const emails = [STAFF_EMAIL, TENANT_EMAIL, ADMIN_EMAIL, 'zz-pw-made@rms.local'];
  const ids = (await prisma.user.findMany({ where: { email: { in: emails } }, select: { id: true } })).map((u) => u.id);
  if (ids.length) {
    await prisma.userRole.deleteMany({ where: { userId: { in: ids } } });
    await prisma.user.deleteMany({ where: { id: { in: ids } } });
  }
  await prisma.tenant.deleteMany({ where: { name: TENANT_NAME } });
}

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); });
