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

interface OrderItemRequest {
  productId: string;
  quantity: number;
  description?: string;
  notes?: string;
}

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

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

    // Validar permissões
    const ctx = await getCompanyContext(supabase, user);
    if (!canCompany(ctx, user.id, "orders.edit")) {
      return NextResponse.json({ error: "Sem permissão para editar pedidos." }, { status: 403 });
    }

    // Validar e parsear request body
    const body: OrderItemRequest = await req.json();
    
    if (!body.productId || !body.quantity) {
      return NextResponse.json(
        { error: "productId e quantity são obrigatórios." },
        { status: 400 }
      );
    }

    if (body.quantity <= 0) {
      return NextResponse.json(
        { error: "quantity deve ser maior que zero." },
        { status: 400 }
      );
    }

    // Buscar order para validar tenant
    const { data: order, error: orderError } = await supabase
      .from("orders")
      .select("tenant_id, status")
      .eq("id", id)
      .single();

    if (orderError || !order) {
      return NextResponse.json(
        { error: "Pedido não encontrado." },
        { status: 404 }
      );
    }

    // Validar se order pertence ao tenant do usuário
    if (order.tenant_id !== ctx.companyId) {
      return NextResponse.json(
        { error: "Pedido não pertence ao seu tenant." },
        { status: 403 }
      );
    }

    // Buscar dados do produto
    const { data: product, error: productError } = await supabase
      .from("products")
      .select("id,name,price,price_on_request,cost_total,estimated_base_cost")
      .eq("id", body.productId)
      .eq("tenant_id", order.tenant_id)
      .single();

    if (productError || !product) {
      return NextResponse.json(
        { error: "Produto não encontrado." },
        { status: 404 }
      );
    }

    const unitPrice = product.price_on_request ? 0 : Number(product.price ?? 0) || 0;
    const costUnit = Number(product.cost_total ?? product.estimated_base_cost ?? 0) || 0;
    const totalPrice = unitPrice * body.quantity;
    const costTotal = costUnit * body.quantity;
    const marginPercentage = unitPrice > 0 ? ((unitPrice - costUnit) / unitPrice) * 100 : 0;

    const { data: newItem, error: insertError } = await supabase
      .from("order_items")
      .insert({
        order_id: id,
        product_id: body.productId,
        description: body.description || product.name,
        notes: body.notes,
        quantity: body.quantity,
        unit_price: unitPrice,
        total_price: totalPrice,
        cost_unit: costUnit,
        cost_total: costTotal,
        margin_percentage: marginPercentage,
        price_locked: false,
      })
      .select()
      .single();

    if (insertError) {
      console.error("Erro ao inserir item:", insertError);
      return NextResponse.json(
        { error: "Erro ao adicionar item ao pedido." },
        { status: 500 }
      );
    }

    return NextResponse.json(newItem);

  } catch (error) {
    console.error("Erro ao adicionar item ao pedido:", error);
    return NextResponse.json(
      { error: "Erro interno ao adicionar item." },
      { status: 500 }
    );
  }
}
