import { NextResponse } from "next/server";
import { canCompany } from "@/lib/company-context";
import { createClient } from "@/lib/supabase-server";
import {
  createReportRuntime,
  deleteReportPreset,
  listReportPresets,
  saveReportPreset,
} from "@/lib/reports/service";
import type { ReportPresetInput } from "@/lib/reports/contracts";

function normalizePreset(body: Record<string, unknown>): ReportPresetInput {
  return {
    id: typeof body.id === "string" ? body.id : undefined,
    name: typeof body.name === "string" ? body.name : "",
    reportKey: typeof body.reportKey === "string" ? (body.reportKey as ReportPresetInput["reportKey"]) : "custom",
    scope: body.scope === "user" ? "user" : "company",
    isFavorite: body.isFavorite === true,
    config: body.config && typeof body.config === "object" ? (body.config as ReportPresetInput["config"]) : {},
  };
}

export async function GET() {
  try {
    const supabase = await createClient();
    const runtime = await createReportRuntime(supabase);

    if (!canCompany(runtime.ctx, runtime.user.id, "reports.read")) {
      return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
    }

    const presets = await listReportPresets(runtime);
    return NextResponse.json({ presets });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Falha ao listar modelos." },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const supabase = await createClient();
    const runtime = await createReportRuntime(supabase);

    if (!canCompany(runtime.ctx, runtime.user.id, "reports.read")) {
      return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
    }

    const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
    const input = normalizePreset(body ?? {});
    if (!input.name.trim()) {
      return NextResponse.json({ error: "Informe o nome do modelo." }, { status: 400 });
    }

    const presets = await saveReportPreset(runtime, input);
    return NextResponse.json({ presets });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Falha ao salvar modelo." },
      { status: 500 }
    );
  }
}

export async function DELETE(req: Request) {
  try {
    const supabase = await createClient();
    const runtime = await createReportRuntime(supabase);

    if (!canCompany(runtime.ctx, runtime.user.id, "reports.read")) {
      return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
    }

    const url = new URL(req.url);
    const presetId = url.searchParams.get("id")?.trim() || "";
    if (!presetId) {
      return NextResponse.json({ error: "Modelo não informado." }, { status: 400 });
    }

    const presets = await deleteReportPreset(runtime, presetId);
    return NextResponse.json({ presets });
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Falha ao remover modelo." },
      { status: 500 }
    );
  }
}
