-- Phase 12: Offer Editor — additive schema for tier designations, public pricing,
-- archive flag, category/ticket dimensions, structured transformation promise, and
-- tier<->services junction. All statements additive/idempotent. No drops/truncates
-- (Data Safety LOCKED).

-- offer_macros: archive flag + short description + category/ticket dimensions +
-- structured transformation promise
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS description text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS category text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS ticket text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS is_archived boolean NOT NULL DEFAULT false;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS cliente_ideale text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS risultato text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS tempo text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS pain text;
ALTER TABLE offer_macros ADD COLUMN IF NOT EXISTS metodo text;

-- offer_micros: tier designation (A/B/C) + manual public price
ALTER TABLE offer_micros ADD COLUMN IF NOT EXISTS tier_letter text;
ALTER TABLE offer_micros ADD COLUMN IF NOT EXISTS public_price numeric(10, 2);

-- CHECK constraint for tier_letter, added separately so the ADD COLUMN above stays
-- idempotent even if the constraint already exists (guarded via DO block).
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'offer_micros_tier_letter_check'
  ) THEN
    ALTER TABLE offer_micros
      ADD CONSTRAINT offer_micros_tier_letter_check
      CHECK (tier_letter IS NULL OR tier_letter IN ('A', 'B', 'C'));
  END IF;
END $$;

-- New junction table: tier (offer_micros) <-> unified services catalog.
-- Additive replacement for legacy offer_micro_services (untouched, points to offer_services).
CREATE TABLE IF NOT EXISTS offer_tier_services (
  tier_id text NOT NULL REFERENCES offer_micros(id) ON DELETE CASCADE,
  service_id text NOT NULL REFERENCES services(id) ON DELETE CASCADE,
  created_at timestamp with time zone DEFAULT now() NOT NULL,
  PRIMARY KEY (tier_id, service_id)
);

CREATE INDEX IF NOT EXISTS offer_tier_services_tier_idx ON offer_tier_services USING btree (tier_id);
