// /api/cf/[id] — Plan 003, Faza F.
//
//   GET   → gisApi.enrichment.cf.get(id)
//   PATCH → gisApi.enrichment.cf.patch(id, body)  (RLS-owned write)
//
// RLS on the gis-api side ensures only the owner sees / mutates the row.
import { NextResponse } from "next/server";
import { getAuthSession } from "@/core/auth/require-auth";
import {
  gisApi,
  GisApiError,
  type CfExtractRow,
} from "@/lib/gis-api-client";

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

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getAuthSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: "missing_id" }, { status: 400 });
  }

  try {
    return NextResponse.json(await gisApi.enrichment.cf.get(id));
  } catch (err) {
    if (err instanceof GisApiError) {
      return NextResponse.json(
        { error: err.code, status: err.status, body: err.body },
        { status: err.status },
      );
    }
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[cf-get] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const session = await getAuthSession();
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: "missing_id" }, { status: 400 });
  }

  let body: Partial<CfExtractRow>;
  try {
    body = (await request.json()) as Partial<CfExtractRow>;
  } catch {
    return NextResponse.json({ error: "invalid_body" }, { status: 400 });
  }

  try {
    return NextResponse.json(await gisApi.enrichment.cf.patch(id, body));
  } catch (err) {
    if (err instanceof GisApiError) {
      return NextResponse.json(
        { error: err.code, status: err.status, body: err.body },
        { status: err.status },
      );
    }
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[cf-patch] internal error:", msg);
    return NextResponse.json(
      { error: "internal_error", hint: msg.slice(0, 200) },
      { status: 500 },
    );
  }
}
