import {
  BadRequestException,
  ConflictException,
  ForbiddenException,
  HttpException,
  InternalServerErrorException,
  NotFoundException,
  PayloadTooLargeException,
  PreconditionFailedException,
  ServiceUnavailableException,
  UnauthorizedException,
  UnprocessableEntityException,
  UnsupportedMediaTypeException,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { TRPCError } from '@trpc/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
import type { AuthUser } from './auth-user';
import { Context, protectedProcedure, publicProcedure, router, staffProcedure, tenantProcedure, withPermission } from './trpc';

/**
 * The back-office / tenant-portal boundary. Both apps share one login endpoint
 * and a token that says nothing about which app issued it, so this middleware is
 * the only thing that keeps a tenant out of the back office — worth pinning down
 * without a database in the way.
 */

const app = router({
  anyLogin: protectedProcedure.query(() => 'ok'),
  staffOnly: staffProcedure.query(() => 'ok'),
  needsPermission: withPermission('invoice.read').query(() => 'ok'),
  tenantOnly: tenantProcedure.query(() => 'ok'),
});

const staff: AuthUser = { id: 'u1', email: 's@x', name: 'Staff', tenantId: null, mustChangePassword: false, roles: ['ADMIN'], permissions: ['invoice.read'] };
const tenant: AuthUser = { id: 'u2', email: 't@x', name: 'Tenant', tenantId: 'tn1', mustChangePassword: false, roles: ['TENANT'], permissions: [] };
/** A tenant login that has somehow been granted a back-office permission — the
 *  configuration the old "the TENANT role is empty" assumption rested on. */
const tenantWithPermission: AuthUser = { ...tenant, permissions: ['invoice.read'] };

const call = (user: AuthUser | null) => app.createCaller({ user } as unknown as Context);

describe('tRPC procedure boundaries', () => {
  it('rejects anonymous callers everywhere', async () => {
    await expect(call(null).anyLogin()).rejects.toThrow('Login required');
    await expect(call(null).staffOnly()).rejects.toThrow('Login required');
    await expect(call(null).tenantOnly()).rejects.toThrow('Login required');
  });

  it('lets a back-office login through', async () => {
    await expect(call(staff).staffOnly()).resolves.toBe('ok');
    await expect(call(staff).needsPermission()).resolves.toBe('ok');
  });

  it('keeps a tenant login out of the back office', async () => {
    await expect(call(tenant).staffOnly()).rejects.toThrow('cannot use the back office');
    await expect(call(tenant).needsPermission()).rejects.toThrow('cannot use the back office');
  });

  it('keeps a tenant out even when their role carries the permission', async () => {
    await expect(call(tenantWithPermission).needsPermission()).rejects.toThrow('cannot use the back office');
  });

  it('still lets both apps rehydrate a session', async () => {
    // `me` is protectedProcedure: the portal calls it on every load, so putting
    // the staff check any lower would log every tenant out.
    await expect(call(tenant).anyLogin()).resolves.toBe('ok');
    await expect(call(staff).anyLogin()).resolves.toBe('ok');
  });

  it('keeps a back-office login out of tenant-scoped procedures', async () => {
    await expect(call(tenant).tenantOnly()).resolves.toBe('ok');
    await expect(call(staff).tenantOnly()).rejects.toThrow('not a tenant');
  });
  it('holds a login that must change its password out of both apps', async () => {
    const staffMust: AuthUser = { ...staff, mustChangePassword: true };
    const tenantMust: AuthUser = { ...tenant, mustChangePassword: true };
    await expect(call(staffMust).staffOnly()).rejects.toThrow('Change your password before continuing');
    await expect(call(staffMust).needsPermission()).rejects.toThrow('Change your password before continuing');
    await expect(call(tenantMust).tenantOnly()).rejects.toThrow('Change your password before continuing');
  });

  it('still lets them rehydrate, or the forced screen has no way out', async () => {
    // The load-bearing half. `me` is protectedProcedure and account.changePassword
    // sits beside it, so tidying this gate up one level would leave the holder
    // unable to fetch their own user or to change the password that is blocking
    // them — locked out permanently, by the feature meant to let them in.
    await expect(call({ ...staff, mustChangePassword: true }).anyLogin()).resolves.toBe('ok');
    await expect(call({ ...tenant, mustChangePassword: true }).anyLogin()).resolves.toBe('ok');
  });
});

/**
 * The services throw NestJS exceptions, which tRPC wraps as
 * INTERNAL_SERVER_ERROR. Before the root middleware recoded them, the formatter
 * hid every one — staff typed a reading backwards and were told the server had
 * failed. These pin both halves: what the service meant reaches the caller, and
 * what is ours still does not.
 */
const failures: Record<string, () => Error> = {
  badRequest: () => new BadRequestException('End reading must be greater than or equal to start'),
  unauthorized: () => new UnauthorizedException('Invalid email or password'),
  forbidden: () => new ForbiddenException('You are not the approver for this step'),
  notFound: () => new NotFoundException('Meter not found'),
  conflict: () => new ConflictException('A meter with that serial number already exists'),
  preconditionFailed: () => new PreconditionFailedException('Precondition failed'),
  payloadTooLarge: () => new PayloadTooLargeException('File exceeds the 10MB limit'),
  unprocessable: () => new UnprocessableEntityException('Unprocessable'),
  tooManyRequests: () => new HttpException('Slow down', 429),
  // Ours, not the caller's: each message below describes our internals.
  internalNest: () => new InternalServerErrorException('The PDF renderer is not available on this server'),
  unavailable: () => new ServiceUnavailableException('Database pool exhausted'),
  unsupportedMedia: () => new UnsupportedMediaTypeException('Not a caller-facing code'),
  plain: () => new TypeError("Cannot read properties of undefined (reading 'readingEnd')"),
  prisma: () =>
    new Prisma.PrismaClientKnownRequestError('Unique constraint failed on the constraint: `Meter_serialNo_key`', {
      code: 'P2002',
      clientVersion: 'test',
    }),
};
const HIDDEN = ['internalNest', 'unavailable', 'unsupportedMedia', 'plain', 'prisma'];
const SHOWN: [string, TRPCError['code'], number][] = [
  ['badRequest', 'BAD_REQUEST', 400],
  ['unauthorized', 'UNAUTHORIZED', 401],
  ['forbidden', 'FORBIDDEN', 403],
  ['notFound', 'NOT_FOUND', 404],
  ['conflict', 'CONFLICT', 409],
  ['preconditionFailed', 'PRECONDITION_FAILED', 412],
  ['payloadTooLarge', 'PAYLOAD_TOO_LARGE', 413],
  ['unprocessable', 'UNPROCESSABLE_CONTENT', 422],
  ['tooManyRequests', 'TOO_MANY_REQUESTS', 429],
];

const fail = ({ input }: { input: string }): never => {
  throw failures[input]();
};
const failing = router({
  asAnyone: publicProcedure.input(z.string()).query(fail),
  asLogin: protectedProcedure.input(z.string()).query(fail),
  asStaff: withPermission('invoice.read').input(z.string()).mutation(fail),
  asTenant: tenantProcedure.input(z.string()).mutation(fail),
});

const failAs = async (key: string) => {
  const errors = await Promise.all([
    failing.createCaller({ user: null } as unknown as Context).asAnyone(key).catch((e: unknown) => e),
    failing.createCaller({ user: staff } as unknown as Context).asLogin(key).catch((e: unknown) => e),
    failing.createCaller({ user: staff } as unknown as Context).asStaff(key).catch((e: unknown) => e),
    failing.createCaller({ user: tenant } as unknown as Context).asTenant(key).catch((e: unknown) => e),
  ]);
  return errors as TRPCError[];
};

/** Through the real HTTP handler, so the formatter and the status are exercised
 *  exactly as a browser meets them — not only the error createCaller rethrows. */
const overHttp = async (key: string) => {
  const logged: TRPCError['code'][] = [];
  const res = await fetchRequestHandler({
    endpoint: '/trpc',
    req: new Request(`http://test/trpc/asAnyone?input=${encodeURIComponent(JSON.stringify(key))}`),
    router: failing,
    createContext: () => ({ user: null }) as unknown as Context,
    onError: ({ error }) => logged.push(error.code),
  });
  const body = (await res.json()) as { error: { message: string; data: { code: string; httpStatus: number } } };
  return { status: res.status, message: body.error.message, code: body.error.data.code, logged };
};

describe('service exceptions over tRPC', () => {
  it('keeps the code and the message a service meant, behind every procedure builder', async () => {
    for (const [key, code] of SHOWN) {
      const thrown = failures[key]();
      for (const error of await failAs(key)) {
        expect(error).toBeInstanceOf(TRPCError);
        expect(error.code).toBe(code);
        expect(error.message).toBe(thrown.message);
        expect(error.cause).toBeInstanceOf(thrown.constructor);
      }
    }
  });

  it('leaves our own failures as INTERNAL_SERVER_ERROR', async () => {
    for (const key of HIDDEN) {
      for (const error of await failAs(key)) {
        expect(error).toBeInstanceOf(TRPCError);
        expect(error.code).toBe('INTERNAL_SERVER_ERROR');
        expect(error.cause).toBeInstanceOf(failures[key]().constructor);
      }
    }
  });

  it('sends a caller-facing failure with its own status and message, and logs it as expected traffic', async () => {
    for (const [key, code, status] of SHOWN) {
      const res = await overHttp(key);
      expect(res).toEqual({ status, message: failures[key]().message, code, logged: [code] });
    }
  });

  it('still hides everything else behind the generic sentence', async () => {
    for (const key of HIDDEN) {
      const res = await overHttp(key);
      expect(res).toEqual({
        status: 500,
        message: 'Something went wrong on the server',
        code: 'INTERNAL_SERVER_ERROR',
        logged: ['INTERNAL_SERVER_ERROR'],
      });
    }
  });

  it('does not recode a TRPCError a procedure threw on purpose', async () => {
    // The auth middleware's UNAUTHORIZED is what the clients renew a session on;
    // it must come through as itself.
    const error = (await failing.createCaller({ user: null } as unknown as Context).asLogin('badRequest').catch((e: unknown) => e)) as TRPCError;
    expect(error.code).toBe('UNAUTHORIZED');
    expect(error.message).toBe('Login required');
  });
});
