import { Logger } from '@nestjs/common';
import type { PrismaClient } from '@prisma/client';
import * as trpcExpress from '@trpc/server/adapters/express';
import type { AuthService } from '../auth/auth.service';
import { hashPassword, verifyPassword } from '../auth/password';
import { appRouter } from './app-router';
import type { ApprovalPort, BillingPort, DepositsPort, DocumentsPort, MaintenancePort, MeteringPort, PaymentsPort, ReportsPort, StatementsPort } from './ports';
import type { Context } from './trpc';

/**
 * Builds the Express middleware that serves the tRPC router. Kept in the Nest
 * boundary (main.ts calls this with resolved providers) so the router modules
 * themselves stay free of framework code.
 */
const log = new Logger('tRPC');

/** Codes that mean the caller did something wrong. They are the normal traffic
 *  of a working system, so they are logged at debug; anything else is a defect
 *  and gets a full stack at error level. */
const EXPECTED = new Set([
  'BAD_REQUEST',
  'UNAUTHORIZED',
  'FORBIDDEN',
  'NOT_FOUND',
  'CONFLICT',
  'PRECONDITION_FAILED',
  'PAYLOAD_TOO_LARGE',
  'UNPROCESSABLE_CONTENT',
  'TOO_MANY_REQUESTS',
]);

export function createTrpcMiddleware(
  prisma: PrismaClient,
  authService: AuthService,
  billing: BillingPort,
  payments: PaymentsPort,
  deposits: DepositsPort,
  metering: MeteringPort,
  maintenance: MaintenancePort,
  approvals: ApprovalPort,
  reports: ReportsPort,
  documents: DocumentsPort,
  statements: StatementsPort,
) {
  return trpcExpress.createExpressMiddleware({
    router: appRouter,
    createContext: async ({ req }): Promise<Context> => {
      const header = req.headers.authorization;
      const token = header?.startsWith('Bearer ') ? header.slice(7) : null;
      const user = token ? await authService.verifyAndLoad(token) : null;

      // Single-organisation for now; multi-org resolves membership here later.
      const org = await prisma.organization.findFirst({
        where: { deletedAt: null },
        select: { id: true },
      });

      return { prisma, user, organizationId: org?.id ?? null, billing, payments, deposits, metering, maintenance, approvals, reports, documents, statements, hashPassword, verifyPassword };
    },
    // Every business operation in the product runs through here. Without this,
    // a Prisma constraint violation or a dropped connection leaves the service
    // log completely clean — no stack, no procedure, no user — and the only
    // evidence is a toast on somebody's screen that nobody wrote down.
    onError({ error, path, type, ctx }) {
      const who = ctx?.user ? `${ctx.user.email} (${ctx.user.id})` : 'anonymous';
      const where = `${type} ${path ?? '<no path>'}`;
      if (EXPECTED.has(error.code)) {
        log.debug(`${error.code} ${where} — ${who}: ${error.message}`);
        return;
      }
      log.error(`${error.code} ${where} — ${who}: ${error.message}`, error.cause instanceof Error ? error.cause.stack : error.stack);
    },
  });
}
