import { createClient } from "@/lib/supabase-server";
import { ApiV1Error } from "@/lib/api-v1/errors";
import { jsonOk, toErrorResponse } from "@/lib/api-v1/response";
import {
  createPaymentLink,
  deletePaymentLink,
  listPaymentLinks,
  resolvePaymentLinksContext,
  updatePaymentLink,
} from "@/lib/api-v1/services/payment-links-service";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const revalidate = 0;

async function resolveRequestContext(request: Request) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return { error: toErrorResponse(new ApiV1Error(401, "unauthorized", "Nao autenticado.")) };
  }

  return resolvePaymentLinksContext({ request, supabase, user });
}

export async function GET(request: Request) {
  try {
    const resolved = await resolveRequestContext(request);
    if ("error" in resolved) return resolved.error;
    return jsonOk(await listPaymentLinks({ resolved }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function POST(request: Request) {
  try {
    const resolved = await resolveRequestContext(request);
    if ("error" in resolved) return resolved.error;
    const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
    return jsonOk(await createPaymentLink({ resolved, body }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function PATCH(request: Request) {
  try {
    const resolved = await resolveRequestContext(request);
    if ("error" in resolved) return resolved.error;
    const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
    const linkId = typeof body?.id === "string" ? body.id.trim() : "";
    if (!linkId) throw new ApiV1Error(400, "invalid_payment_link", "Link invalido.");
    return jsonOk(await updatePaymentLink({ resolved, id: linkId, body }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function DELETE(request: Request) {
  try {
    const resolved = await resolveRequestContext(request);
    if ("error" in resolved) return resolved.error;
    const { searchParams } = new URL(request.url);
    const linkId = String(searchParams.get("id") || "").trim();
    if (!linkId) throw new ApiV1Error(400, "invalid_payment_link", "Link invalido.");
    return jsonOk(await deletePaymentLink({ resolved, id: linkId }));
  } catch (error) {
    return toErrorResponse(error);
  }
}
