
import { NextResponse } from "next/server";
import { createAdminClient, createClient } from "@/lib/supabase-server";
import { canCompany, getCompanyContext } from "@/lib/company-context";

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

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

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

  const { searchParams } = new URL(req.url);
  const productId = searchParams.get("productId");

  if (!productId) {
    return NextResponse.json({ error: "Product ID required" }, { status: 400 });
  }

  const adminSupabase = createAdminClient();

  // We use explicit foreign key syntax to avoid ambiguity, especially for labor_roles which has multiple FKs
  const [matRes, procRes] = await Promise.all([
    adminSupabase
      .from('product_materials')
      .select('*, materials!material_id(name, unit, cost_per_unit, track_stock, is_service, grade, papel)')
      .eq('product_id', productId)
      .order('ordem', { nullsFirst: false })
      .order('id'),
    adminSupabase
      .from('product_processes')
      .select('*, machines!machine_id(name, hourly_cost), labor_roles!role_id(role_name, hourly_rate)')
      .eq('product_id', productId)
      .order('sequence_order')
  ]);

  if (matRes.error) {
    console.error("Error fetching materials:", matRes.error);
    return NextResponse.json({ error: `Materials error: ${matRes.error.message}` }, { status: 400 });
  }
  if (procRes.error) {
    console.error("Error fetching processes:", procRes.error);
    // If explicit FK fails, try legacy or default relationship as fallback for labor_roles
    if (procRes.error.message.includes("relationship")) {
        const retryRes = await adminSupabase
          .from('product_processes')
          .select('*, machines(name, hourly_cost), labor_roles(role_name, hourly_rate)')
          .eq('product_id', productId)
          .order('sequence_order');
        
        if (!retryRes.error) {
             return NextResponse.json({
                materials: matRes.data,
                processes: retryRes.data
              });
        }
    }
    return NextResponse.json({ error: `Processes error: ${procRes.error.message}` }, { status: 400 });
  }

  return NextResponse.json({
    materials: matRes.data,
    processes: procRes.data
  });
}
