import { requireApiV1Auth } from "@/lib/api-v1/auth";
import { apiJsonOk, toApiErrorResponse } from "@/lib/api-v1/response";
import {
  createPaymentLink,
  listPaymentLinks,
  resolvePaymentLinksContext,
} from "@/lib/api-v1/services/payment-links-service";
import { applyApiRateLimit } from "@/lib/api-v1/rate-limit";
import { optionalTrimmedString, parseJsonObject } from "@/lib/api-v1/validators";

export async function GET(request: Request) {
  try {
    const auth = await requireApiV1Auth(request, "financial.links.read");
    const resolved = await resolvePaymentLinksContext({
      request,
      supabase: auth.supabase,
      user: auth.user,
      admin: auth.admin,
    });
    optionalTrimmedString(new URL(request.url).searchParams.get("lookup"));
    optionalTrimmedString(new URL(request.url).searchParams.get("q"));
    const rateLimit = applyApiRateLimit(
      request,
      {
        namespace: "api-v1:payment-links:get",
        windowMs: 60_000,
        maxPerIp: 120,
        maxPerUser: 120,
      },
      auth.user.id
    );
    const result = await listPaymentLinks({ resolved });
    return apiJsonOk({ items: result.links }, { headers: rateLimit.headers });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: Request) {
  try {
    const auth = await requireApiV1Auth(request, "financial.links.write");
    const resolved = await resolvePaymentLinksContext({
      request,
      supabase: auth.supabase,
      user: auth.user,
      admin: auth.admin,
    });
    const rateLimit = applyApiRateLimit(
      request,
      {
        namespace: "api-v1:payment-links:post",
        windowMs: 60_000,
        maxPerIp: 60,
        maxPerUser: 60,
      },
      auth.user.id
    );
    const body = await parseJsonObject(request);
    const result = await createPaymentLink({ resolved, body });
    return apiJsonOk(result.link, { headers: rateLimit.headers });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
