import { prisma } from "@pmap/database";
import { calculateRate } from "@pmap/utilities";
import { fail, ok } from "../../_lib";

export async function GET(request: Request) {
  try {
    const now = new Date();
    const rates = await prisma.registrationRate.findMany({
      where: {
        active: true,
        published: true,
        startsAt: { lte: now },
        endsAt: { gte: now },
        period: { isActive: true, isPublished: true, startsAt: { lte: now }, endsAt: { gte: now } }
      },
      orderBy: [{ displayOrder: "asc" }, { name: "asc" }],
      take: 50
    });
    return ok(request, rates.map((rate) => ({
      id: rate.id,
      name: rate.name,
      code: rate.code,
      participantCategory: rate.participantCategory,
      currency: rate.currency,
      amount: calculateRate({
        baseAmount: rate.baseAmount.toString(),
        discount: rate.discountAmount.toString(),
        vatRate: rate.vatRate.toString(),
        vatInclusive: rate.vatInclusive
      })
    })));
  } catch (error) {
    return fail(request, "RATES_UNAVAILABLE", "Registration rates could not be loaded.", 500, error instanceof Error ? error.message : error);
  }
}
