-- Phase 21/22: Proposals — preventivo AI generato + pagina pubblica navigabile.
-- Additive only. No drops/truncates (Data Safety LOCKED).
-- Applicare a prod via SSH tunnel PRIMA di pushare il codice dipendente.
--
-- content (jsonb): l'intero ProposalContent assemblato (sezioni AI + offerta + config).
-- slug: identificatore pubblico URL-safe per /preventivo/[slug].
-- selected_tier: 'A' | 'B' | 'C' scelto dal cliente in fase di accettazione.
-- accepted_at: IMMUTABILE una volta valorizzato (audit, pattern quotes/deliverables).

CREATE TABLE IF NOT EXISTS proposals (
  id             text PRIMARY KEY NOT NULL,
  slug           text UNIQUE NOT NULL,
  lead_id        text REFERENCES leads(id) ON DELETE SET NULL,
  client_id      text REFERENCES clients(id) ON DELETE SET NULL,
  offer_macro_id text NOT NULL REFERENCES offer_macros(id) ON DELETE RESTRICT,
  title          text,
  content        jsonb NOT NULL,
  model          text,
  state          text NOT NULL DEFAULT 'draft', -- draft | published | accepted | rejected
  selected_tier  text CHECK (selected_tier IN ('A', 'B', 'C')),
  accepted_at    timestamp with time zone,
  client_email   text,
  client_notes   text,
  created_at     timestamp with time zone NOT NULL DEFAULT now(),
  updated_at     timestamp with time zone NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS proposals_slug_idx ON proposals (slug);
CREATE INDEX IF NOT EXISTS proposals_client_id_idx ON proposals (client_id);
CREATE INDEX IF NOT EXISTS proposals_lead_id_idx ON proposals (lead_id);
CREATE INDEX IF NOT EXISTS proposals_offer_macro_id_idx ON proposals (offer_macro_id);
