
import { NextResponse } from "next/server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { createClient } from "@/lib/supabase-server";
import { canCompany, getCompanyContext } from "@/lib/company-context";
import { custoDoProduto } from "@/lib/precificacao/custo-do-produto";

type CostRow = { cost_total?: number | null };

export async function POST(req: Request) {
  const { supabase, user } = await getAuth();
  if (!user) return NextResponse.json({ error: "Não autenticado." }, { status: 401 });

  const ctx = await getCompanyContext(supabase, user);
  if (!canCompany(ctx, user.id, "products.catalog.write")) {
    return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
  }

  const body = (await req.json()) as Record<string, unknown>;
  const product_id = typeof body.product_id === "string" ? body.product_id : "";

  const { data, error } = await supabase
    .from("product_materials")
    .insert({
      ...body,
      user_id: ctx.ownerId ?? ctx.companyId,
    })
    .select()
    .single();

  if (error) return NextResponse.json({ error: error.message }, { status: 400 });

  await updateProductCost(supabase, product_id);

  return NextResponse.json({ ok: true, data });
}

export async function DELETE(req: Request) {
  const { supabase, user } = await getAuth();
  if (!user) return NextResponse.json({ error: "Não autenticado." }, { status: 401 });

  const body = (await req.json()) as Record<string, unknown>;
  const id = typeof body.id === "string" ? body.id : "";
  const product_id = typeof body.product_id === "string" ? body.product_id : "";

  const { error } = await supabase
    .from("product_materials")
    .delete()
    .eq("id", id);

  if (error) return NextResponse.json({ error: error.message }, { status: 400 });

  await updateProductCost(supabase, product_id);

  return NextResponse.json({ ok: true });
}

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

async function updateProductCost(supabase: SupabaseClient, productId: string) {
  const { data: prod } = await supabase
    .from("products")
    .select("estimated_base_cost,unit_type,pricing_reference_width_m,pricing_reference_height_m")
    .eq("id", productId)
    .single();
    
  const estimated = Number(prod?.estimated_base_cost || 0);

  const { data: processes } = await supabase
    .from("product_processes")
    .select("cost_total")
    .eq("product_id", productId);
  const procCost = (processes as CostRow[] | null)?.reduce(
    (acc, p) => acc + (Number(p.cost_total) || 0),
    0
  ) || 0;

  const { data: materials } = await supabase
    .from("product_materials")
    .select("cost_total")
    .eq("product_id", productId);
  const matCost = (materials as CostRow[] | null)?.reduce(
    (acc, m) => acc + (Number(m.cost_total) || 0),
    0
  ) || 0;

  /* Ciente de unidade: a ficha e por peca de referencia; no produto medido a
     unidade de venda e o m². A soma cega dobrava o custo. */
  const newTotal = custoDoProduto({
    estimatedBaseCost: estimated,
    somaDaFicha: procCost + matCost,
    unitType: (prod as { unit_type?: string | null } | null)?.unit_type,
    referenceWidthM: (prod as { pricing_reference_width_m?: number | null } | null)?.pricing_reference_width_m,
    referenceHeightM: (prod as { pricing_reference_height_m?: number | null } | null)?.pricing_reference_height_m,
  });

  await supabase
    .from("products")
    .update({ cost_total: newTotal })
    .eq("id", productId);
}
