-- Phase 9: Quote Validators & Service Layer (Additive Migration)
-- This migration adds missing columns to quotes table for Phase 9 quote builder.
-- ZERO DATA LOSS: All changes are additive. No drops, no truncates, no deletes.
--
-- Why: The Phase 8 migration created quotes table but was missing some required fields
-- for Phase 9 quote acceptance workflow:
-- - accepted_total: immutable snapshot of agreed-upon total (separate from total_amount)
-- - state: refined state machine (replaces status)
-- - client_email: captured on accept
-- - client_notes: captured on accept
-- - Make offer_micro_id NOT NULL (which offer was quoted)
--
-- Backward Compatibility: existing quote rows will have NULLs in new columns

-- Add missing columns to quotes table
ALTER TABLE quotes ADD COLUMN IF NOT EXISTS accepted_total NUMERIC(10, 2);
ALTER TABLE quotes ADD COLUMN IF NOT EXISTS client_email TEXT;
ALTER TABLE quotes ADD COLUMN IF NOT EXISTS client_notes TEXT;

-- Add state column (rename status later if needed, but keep both for now for compatibility)
ALTER TABLE quotes ADD COLUMN IF NOT EXISTS state TEXT DEFAULT 'draft' CHECK (state IN ('draft', 'sent', 'viewed', 'accepted', 'rejected'));

-- Ensure token has a default nanoid generator (handled at application level for existing rows)
-- New rows will use nanoid() via application code

-- Add index for state machine queries
CREATE INDEX IF NOT EXISTS idx_quotes_state ON quotes(state);

-- Update quote_items table to ensure offer_phase_id is properly set for new items
-- Existing rows with NULL offer_phase_id are legacy items from Phase 1-8
-- They remain tied to projects; new items use quotes + offer_phases

-- Add created_at to quote_items for audit trail
ALTER TABLE quote_items ADD COLUMN IF NOT EXISTS created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP;

-- Ensure service_id references the unified services table (not service_catalog)
-- This is enforced at schema level; migration handles existing references
-- No structural change needed here — quote_items.service_id already references service_catalog
-- Phase 9+ will reference services table for new items

CREATE INDEX IF NOT EXISTS idx_quote_items_created_at ON quote_items(created_at);
