import type { PrismaClient } from '@prisma/client';
import { initTRPC, TRPCError } from '@trpc/server';
import type { AuthUser } from './auth-user';
import type { ApprovalPort, BillingPort, DepositsPort, DocumentsPort, MaintenancePort, MeteringPort, PaymentsPort, ReportsPort, StatementsPort } from './ports';

export interface Context {
  prisma: PrismaClient;
  user: AuthUser | null;
  organizationId: string | null;
  billing: BillingPort;
  payments: PaymentsPort;
  deposits: DepositsPort;
  metering: MeteringPort;
  maintenance: MaintenancePort;
  approvals: ApprovalPort;
  reports: ReportsPort;
  documents: DocumentsPort;
  statements: StatementsPort;
  /** Hashes a plaintext password (server-only impl injected by the adapter). */
  hashPassword: (plain: string) => string;
  /** Checks a plaintext password against a stored hash, injected the same way. */
  verifyPassword: (plain: string, stored: string) => boolean;
}

/** Errors that are the caller's business — a validation failure, a missing row,
 *  a refused transition. Everything else is ours, and its message describes our
 *  internals: a Prisma message naming a table and a constraint, a TypeError from
 *  a bad assumption. tRPC's default shape ships that message to the browser
 *  verbatim, where it also sails straight through the errors.json translation
 *  layer untranslated. */
const CALLER_FACING = new Set([
  'BAD_REQUEST',
  'UNAUTHORIZED',
  'FORBIDDEN',
  'NOT_FOUND',
  'CONFLICT',
  'PRECONDITION_FAILED',
  'PAYLOAD_TOO_LARGE',
  'UNPROCESSABLE_CONTENT',
  'TOO_MANY_REQUESTS',
]);

const t = initTRPC.context<Context>().create({
  errorFormatter({ shape, error }) {
    if (CALLER_FACING.has(error.code)) return shape;
    // Replaced with something the caller can act on and that the catalogs can
    // translate. The real message is on the server log — see onError below.
    return { ...shape, message: 'Something went wrong on the server' };
  },
});

/** The status a NestJS HttpException carries, for each CALLER_FACING code — and
 *  only those. A 5xx from a service is still our failure, so it stays unmapped
 *  and the formatter keeps hiding it. */
const CODE_BY_HTTP_STATUS = new Map<number, TRPCError['code']>([
  [400, 'BAD_REQUEST'],
  [401, 'UNAUTHORIZED'],
  [403, 'FORBIDDEN'],
  [404, 'NOT_FOUND'],
  [409, 'CONFLICT'],
  [412, 'PRECONDITION_FAILED'],
  [413, 'PAYLOAD_TOO_LARGE'],
  [422, 'UNPROCESSABLE_CONTENT'],
  [429, 'TOO_MANY_REQUESTS'],
]);

interface HttpExceptionLike extends Error {
  getStatus(): number;
  getResponse(): unknown;
}

/** Recognised by shape, not `instanceof`: the admin app type-imports AppRouter
 *  through this file, and @nestjs/common has no business in its type graph. */
const isHttpException = (e: unknown): e is HttpExceptionLike =>
  e instanceof Error &&
  typeof (e as Partial<HttpExceptionLike>).getStatus === 'function' &&
  typeof (e as Partial<HttpExceptionLike>).getResponse === 'function';

/** The services throw NestJS exceptions — `BadRequestException('End reading
 *  must be greater than or equal to start')` is written for the person who typed
 *  the reading. tRPC has never heard of them and wraps each one as
 *  INTERNAL_SERVER_ERROR, so the formatter above replaced every such message
 *  with the generic sentence, the response went out as a 500, and the adapter
 *  logged a typo as a defect with a full stack. Recoded here, before any of
 *  those look at it. In v11 a failure further down comes back from `next()` as
 *  a result rather than a throw; throwing from here replaces that result. */
const nestHttpExceptions = t.middleware(async ({ next }) => {
  const result = await next();
  if (result.ok || result.error.code !== 'INTERNAL_SERVER_ERROR') return result;
  const cause = result.error.cause;
  if (!isHttpException(cause)) return result;
  const code = CODE_BY_HTTP_STATUS.get(cause.getStatus());
  if (!code) return result;
  throw new TRPCError({ code, message: cause.message, cause });
});

/** Every procedure starts here — nothing builds on t.procedure directly — so no
 *  builder can skip the recoding above. */
const baseProcedure = t.procedure.use(nestHttpExceptions);

export const router = t.router;
export const publicProcedure = baseProcedure;

/** Requires a logged-in user; narrows ctx.user to non-null downstream. */
export const protectedProcedure = baseProcedure.use(({ ctx, next }) => {
  if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Login required' });
  return next({ ctx: { ...ctx, user: ctx.user } });
});

/** Requires a back-office login — one not tied to a tenant party. The boundary
 * between the two apps is here and nowhere else: both share `/auth/login` and a
 * token that says nothing about which app issued it, so without this a portal
 * account reaches every staff procedure its role happens to permit, and the
 * whole back office rests on the TENANT role being left empty.
 *
 * Deliberately NOT folded into protectedProcedure: `me` is how the portal
 * rehydrates its session, and tenantProcedure builds on it — either would log
 * every tenant out. The must-change gate below sits here for the same reason:
 * the forced screen needs `me` to rehydrate once the password is replaced, and
 * account.changePassword itself has to stay reachable, so putting it one level
 * up would leave the holder with no way out. */
export const staffProcedure = protectedProcedure.use(({ ctx, next }) => {
  if (ctx.user.mustChangePassword) {
    throw new TRPCError({ code: 'FORBIDDEN', message: 'Change your password before continuing' });
  }
  if (ctx.user.tenantId) {
    throw new TRPCError({ code: 'FORBIDDEN', message: 'This is a tenant account and cannot use the back office' });
  }
  return next();
});

/** Every key some procedure actually checks, collected as the routers are
 *  built. The seed grants four actions per resource whether or not anything
 *  enforces them, so without this the role editor offers ~21 checkboxes that do
 *  nothing — whole groups of them for resources with no gate at all. Filled at
 *  import time, so it is complete before the first request. */
export const ENFORCED_PERMISSIONS = new Set<string>();

/** Requires a specific permission (RBAC comes from the DB, not hardcoded roles). */
export const withPermission = (permission: string) => {
  ENFORCED_PERMISSIONS.add(permission);
  return staffProcedure.use(({ ctx, next }) => {
    if (!ctx.user.permissions.includes(permission)) {
      throw new TRPCError({ code: 'FORBIDDEN', message: `Missing permission: ${permission}` });
    }
    return next();
  });
};

/** Requires the login to belong to a tenant party; exposes `tenantId` non-null.
 * Every tenant-portal query scopes to this id, so a tenant only sees their own. */
export const tenantProcedure = protectedProcedure.use(({ ctx, next }) => {
  if (ctx.user.mustChangePassword) {
    throw new TRPCError({ code: 'FORBIDDEN', message: 'Change your password before continuing' });
  }
  if (!ctx.user.tenantId) {
    throw new TRPCError({ code: 'FORBIDDEN', message: 'This account is not a tenant' });
  }
  return next({ ctx: { ...ctx, tenantId: ctx.user.tenantId } });
});
