import type { ProposalContent } from "./schema";
import type { OfferEditorData } from "@/lib/offer-queries";
import { CONSULTANT_PROFILE } from "./profile";
import type { Client, Lead } from "@/db/schema";

// Struttura completa salvata in proposals.content (jsonb)
export type AssembledProposal = {
  // Metadati di generazione
  generatedAt: string; // ISO string
  model: string;

  // Intestazione (cover + vision)
  header: {
    clientName: string;       // es. "Yeldo"
    consultantName: string;
    offerTitle: string;
    offerDescription: string | null;
    date: string;             // "DD MMM YYYY" formattata in italiano
    validityDays: number;
  };

  // Sezioni generate dall'AI
  ai: ProposalContent;

  // Profilo consulente (snapshot al momento della generazione)
  consultant: typeof CONSULTANT_PROFILE;

  // Dati offerta dal DB (snapshot — prezzi al momento della generazione)
  offer: {
    macroId: string;
    publicName: string;
    offerType: string; // una_tantum | retainer
    tiers: Array<{
      id: string;
      tierLetter: string;
      publicName: string;
      publicPrice: string | null;
      servicesTotal: string;
      durationMonths: number;
      services: Array<{ id: string; name: string; unitPrice: string }>;
    }>;
  };
};

type AssembleInput = {
  lead?: Pick<Lead, "id" | "name" | "company">;
  client?: Pick<Client, "id" | "name" | "brand_name">;
  offer: OfferEditorData;
  aiContent: ProposalContent;
  model: string;
};

export function assembleProposal(input: AssembleInput): AssembledProposal {
  const clientName =
    input.client?.brand_name ?? input.lead?.company ?? input.lead?.name ?? "Cliente";

  const offerTitle = input.offer.macro.public_name;

  // Formatta data in italiano
  const now = new Date();
  const date = now.toLocaleDateString("it-IT", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });

  // Snapshot servizi per tier (solo quelli assegnati)
  const tiers = input.offer.tiers.map((tier) => {
    const assignedServices = input.offer.availableServices.filter((s) =>
      tier.assignedServiceIds.includes(s.id)
    );
    return {
      id: tier.id,
      tierLetter: tier.tier_letter ?? "",
      publicName: tier.public_name,
      publicPrice: tier.public_price,
      servicesTotal: tier.servicesTotal,
      durationMonths: tier.duration_months,
      services: assignedServices.map((s) => ({
        id: s.id,
        name: s.name,
        unitPrice: s.unit_price,
      })),
    };
  });

  return {
    generatedAt: now.toISOString(),
    model: input.model,
    header: {
      clientName,
      consultantName: CONSULTANT_PROFILE.name,
      offerTitle,
      offerDescription: input.offer.macro.description ?? null,
      date,
      validityDays: CONSULTANT_PROFILE.legal.validityDays,
    },
    ai: input.aiContent,
    consultant: CONSULTANT_PROFILE,
    offer: {
      macroId: input.offer.macro.id,
      publicName: offerTitle,
      offerType: input.offer.macro.offer_type ?? "una_tantum",
      tiers,
    },
  };
}
