import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { getPagamentoDataForCheckout } from "~/server/controllers/servizio.controller";
import { db } from "~/server/db";
import { zPagamentoId } from "~/server/utils/zod_types";
// Create a new ratelimiter, that allows 10 requests per 10 seconds
/*
const ratelimit = new RateLimiterHandler({
  maxRequests: 10,
  windowSize: 60,
  analytics: false,
});
*/

export const pagamentiRouter = createTRPCRouter({
	getPaymentFromIntent: protectedProcedure
		.input(z.object({ pIntentId: z.string() }))
		.query(async ({ input }) => {
			try {
				return (
					(await db
						.selectFrom("payments")
						.selectAll("payments")
						.where("payments.intent_id", "=", input.pIntentId)
						.executeTakeFirst()) || null
				);
			} catch (error) {
				throw new TRPCError({
					code: "INTERNAL_SERVER_ERROR",
					message: `Error retriving payment: ${(error as Error).message}`,
				});
			}
		}),

	getPagamentoDataForCheckout: protectedProcedure
		.input(z.object({ paymentId: zPagamentoId }))
		.query(async ({ input }) => {
			return await getPagamentoDataForCheckout(input.paymentId);
		}),
});
