import { createClient } from "@/lib/supabase-server";
import { ApiV1Error } from "@/lib/api-v1/errors";
import { toErrorResponse, jsonOk } from "@/lib/api-v1/response";
import {
  createCategory,
  deleteCategory,
  listCategories,
  updateCategory,
} from "@/lib/api-v1/services/categories-service";

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

export async function GET() {
  try {
    const { supabase, user } = await getAuth();
    if (!user) throw new ApiV1Error(401, "unauthorized", "Nao autenticado.");
    return jsonOk(await listCategories({ supabase, user }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function POST(req: Request) {
  try {
    const { supabase, user } = await getAuth();
    if (!user) throw new ApiV1Error(401, "unauthorized", "Nao autenticado.");
    const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
    return jsonOk(await createCategory({ supabase, user, body, request: req }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function PATCH(req: Request) {
  try {
    const { supabase, user } = await getAuth();
    if (!user) throw new ApiV1Error(401, "unauthorized", "Nao autenticado.");
    const body = (await req.json().catch(() => null)) as { id?: unknown; patch?: unknown } | null;
    const id = typeof body?.id === "string" ? body.id : "";
    return jsonOk(await updateCategory({ supabase, user, id, patch: body?.patch, request: req }));
  } catch (error) {
    return toErrorResponse(error);
  }
}

export async function DELETE(req: Request) {
  try {
    const { supabase, user } = await getAuth();
    if (!user) throw new ApiV1Error(401, "unauthorized", "Nao autenticado.");
    const body = (await req.json().catch(() => null)) as { id?: unknown } | null;
    const id = typeof body?.id === "string" ? body.id : "";
    return jsonOk(await deleteCategory({ supabase, user, id, request: req }));
  } catch (error) {
    return toErrorResponse(error);
  }
}
