import { NOT_ADMIN_ERR_MSG, UNAUTHED_ERR_MSG } from '@shared/const';
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import type { TrpcContext } from "./context";

const t = initTRPC.context<TrpcContext>().create({
  transformer: superjson,
});

export const router = t.router;

// Imports for security
import { checkRateLimit, checkOrigin } from "./security";

const securityMiddleware = t.middleware(async ({ ctx, next, type, path }) => {
  // CSRF Check for mutations
  if (type === 'mutation') {
    const isAllowed = checkOrigin(ctx.req);
    // Enforcing CSRF check. If this breaks legitimate clients, add them to allowed origins in security.ts
    // For now we allow if valid.
    if (!isAllowed) {
      console.warn(`[Security] CSRF blocked: ${ctx.req.headers.origin} -> ${path}`);
      throw new TRPCError({ code: "FORBIDDEN", message: "Action non autorisée (source invalide)" });
    }
  }

  // Rate Limiting
  const ip = ctx.req.ip || "unknown";
  try {
    // Generous limit for authenticated/general usage, but strict enough to prevent obvious abuse
    // 60 requests per minute per IP for tRPC calls
    checkRateLimit(`trpc:${ip}`, 60, 60 * 1000);
  } catch (error) {
    throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Trop de requêtes. Veuillez patienter." });
  }

  return next({
    ctx: {
      ...ctx,
    },
  });
});

const requireUser = t.middleware(async opts => {
  const { ctx, next } = opts;

  if (!ctx.user) {
    throw new TRPCError({ code: "UNAUTHORIZED", message: UNAUTHED_ERR_MSG });
  }

  return next({
    ctx: {
      ...ctx,
      user: ctx.user,
    },
  });
});

export const publicProcedure = t.procedure.use(securityMiddleware);
export const protectedProcedure = t.procedure.use(securityMiddleware).use(requireUser);

export const adminProcedure = t.procedure.use(
  t.middleware(async opts => {
    const { ctx, next } = opts;

    if (!ctx.user || ctx.user.role !== 'admin') {
      throw new TRPCError({ code: "FORBIDDEN", message: NOT_ADMIN_ERR_MSG });
    }

    return next({
      ctx: {
        ...ctx,
        user: ctx.user,
      },
    });
  }),
);
