import { createClient } from "@/lib/supabase-server";
import { approveQuote } from "@/lib/api-v1/services/quotes-service";
import { ApiV1Error } from "@/lib/api-v1/errors";
import { jsonOk, toErrorResponse } from "@/lib/api-v1/response";

export const runtime = "nodejs";

async function getAuth() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  return { supabase, user };
}

export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  try {
    const params = await ctx.params;
    const quoteId = params.id;
    const { supabase, user } = await getAuth();
    if (!user) throw new ApiV1Error(401, "unauthorized", "Nao autenticado.");

    const result = await approveQuote({ supabase, user, quoteId });

    return jsonOk({ ok: true, orderId: result.orderId });
  } catch (error) {
    return toErrorResponse(error);
  }
}
