import {
  formatCurrency,
  formatDecimal,
  formatInteger,
  formatPercent,
} from "./utils";

export function buildMetricCards(summary, options = {}) {
  const { isAllPropertiesSelected = false, referenceLabel = "" } = options;

  const displayedExpenses =
    Number(summary.expenses_amount ?? 0) + Number(summary.ota_amount ?? 0);

  const maintenanceExpenseAmount = Number(
    summary.expenses_breakdown?.items
      ?.filter((expense) => expense.source === "manual")
      ?.filter((expense) => expense.category === "maintenance")
      ?.reduce(
        (total, expense) => total + Number(expense.final_amount ?? 0),
        0,
      ) ?? 0,
  );

  const occupancyCaption = isAllPropertiesSelected
    ? "percentual do período"
    : `${formatInteger(summary.occupied_nights_in_month)} de ${formatInteger(summary.days_in_month)} dias`;

  return [
    // INDICADORES

    {
      label: "Ocupação",
      value: formatPercent(summary.occupancy_rate, 1),
      caption: occupancyCaption,
    },

    {
      label: "Total de Reservas",
      value: formatInteger(summary.reservations_count),
      caption: "no período",
    },

    {
      label: "Dias por Reserva",
      value: formatDecimal(summary.average_nights_per_reservation),
      caption: "média de permanência",
    },

    {
      label: "Diária Média",
      value: formatCurrency(summary.average_price_per_night),
      caption: "Bruto ÷ diárias",
    },

    {
      label: "Limpezas",
      value: formatInteger(summary.cleanings_count),
      caption: "total no período",
    },

    {
      label: "Manutenção",
      value: formatCurrency(maintenanceExpenseAmount),
      caption: "despesas manuais",
    },

    {
      label: "Ticket Médio/Reserva",
      value: formatCurrency(summary.average_reservation_ticket),
      caption: isAllPropertiesSelected
        ? "Todos apartamentos"
        : "No imóvel selecionado",
    },

    // FINANCEIRO

    {
      label: "Faturamento",
      value: formatCurrency(summary.gross_revenue),
      caption: referenceLabel || "Mês selecionado",
    },

    {
      label: "OTA",
      value: formatCurrency(summary.ota_amount),
      caption: "taxas plataformas",
    },

    {
      label: "Faturamento Líquido",
      value: formatCurrency(summary.net_revenue_amount),
      caption: "Bruto - OTA",
    },

    {
      label: "Total Limpeza",
      value: formatCurrency(summary.cleaning_total_amount),
      caption: "taxa de limpeza",
    },

    {
      label: "Gestão Kizzo",
      value: formatCurrency(summary.management_fee_amount),
      caption: "comissão gestão",
    },

    {
      label: "Despesas",
      value: formatCurrency(displayedExpenses),
      caption: "inclui OTA",
    },

    {
      label: "Repasse",
      value: formatCurrency(summary.payout_amount),
      caption: isAllPropertiesSelected
        ? "Todos apartamentos"
        : "No imóvel selecionado",
    },
  ];
}
