"use server";

import { createClient } from "@/lib/supabase-server";
import { revalidatePath } from "next/cache";
import { canCompany, getCompanyContext } from "@/lib/company-context";
import { registrarPagamentoDoPedido } from "@/lib/financeiro/pagamento-do-pedido";

function parseMoneyValue(value: FormDataEntryValue | null) {
  const raw = String(value ?? "").trim();
  if (!raw) return Number.NaN;
  const sanitized = raw
    .replace(/\s/g, "")
    .replace(/R\$/gi, "");
  const hasComma = sanitized.includes(",");
  const hasDot = sanitized.includes(".");
  let normalized = sanitized;

  if (hasComma && hasDot) {
    const lastComma = sanitized.lastIndexOf(",");
    const lastDot = sanitized.lastIndexOf(".");
    normalized =
      lastComma > lastDot
        ? sanitized.replace(/\./g, "").replace(",", ".")
        : sanitized.replace(/,/g, "");
  } else if (hasComma) {
    normalized = sanitized.replace(",", ".");
  } else if (hasDot) {
    normalized = sanitized.replace(/,/g, "");
  }
  return Number.parseFloat(normalized);
}

export async function registerPayment(formData: FormData) {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return { error: "Usuário não autenticado" };
  }

  const ctx = await getCompanyContext(supabase, user);
  const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
  if (!canCompany(ctx, user.id, "financial.receivables.settle")) {
    return { error: "Sem permissão para registrar pagamentos." };
  }

  const orderId = formData.get("orderId") as string;
  const amount = parseMoneyValue(formData.get("amount"));
  const paymentMethod = formData.get("paymentMethod") as string;
  const paymentDateTime = formData.get("paymentDateTime") as string | null;
  const paymentDate = formData.get("paymentDate") as string | null;
  const tzOffsetMinutesRaw = formData.get("tzOffsetMinutes") as string | null;
  const notes = formData.get("notes") as string;
  const bankAccountIdRaw = formData.get("bankAccountId") as string | null;

  const resultado = await registrarPagamentoDoPedido(supabase, { userId: user.id, tenantIds }, {
    orderId,
    amount,
    paymentMethod,
    paymentDateTime,
    paymentDate,
    tzOffsetMinutesRaw,
    notes,
    bankAccountIdRaw,
  });
  if ("error" in resultado) {
    return { error: resultado.error };
  }

  revalidatePath(`/dashboard/orders/${orderId}`);
  return { success: true };
}

export async function deletePayment(paymentId: string, orderId: string) {
  const supabase = await createClient();

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return { error: "Usuário não autenticado" };
  }

  const ctx = await getCompanyContext(supabase, user);
  if (!canCompany(ctx, user.id, "financial.receivables.settle")) {
    return { error: "Sem permissão para excluir pagamentos." };
  }

  const { error } = await supabase.rpc("delete_payment_with_cleanup", {
    p_payment_id: paymentId,
    p_order_id: orderId,
  });

  if (error) {
    console.error("Error deleting payment:", error);
    return { error: error.message || "Erro ao excluir pagamento" };
  }

  revalidatePath(`/dashboard/orders/${orderId}`);
  return { success: true };
}

export async function updatePaymentNotes(paymentId: string, orderId: string, notes: string) {
  const supabase = await createClient();

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user) {
    return { error: "Usuário não autenticado" };
  }

  const ctx = await getCompanyContext(supabase, user);
  const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
  if (!canCompany(ctx, user.id, "financial.receivables.settle")) {
    return { error: "Sem permissão para editar pagamentos." };
  }

  const trimmedNotes = notes.trim();

  const { data: payment, error: paymentError } = await supabase
    .from("payments")
    .select("id, order_id, user_id")
    .eq("id", paymentId)
    .eq("order_id", orderId)
    .in("user_id", tenantIds)
    .maybeSingle();

  if (paymentError || !payment) {
    return { error: "Pagamento não encontrado." };
  }

  const { error } = await supabase
    .from("payments")
    .update({ notes: trimmedNotes || null })
    .eq("id", paymentId)
    .eq("order_id", orderId)
    .in("user_id", tenantIds);

  if (error) {
    console.error("Error updating payment notes:", error);
    return { error: error.message || "Erro ao atualizar observação do pagamento." };
  }

  revalidatePath(`/dashboard/orders/${orderId}`);
  return { success: true };
}
