-- lead-qualification-scoring (wave-14)
-- Adds score + score_updated_at to leads, partial score index,
-- and lead_scoring_criteria column to tenant_settings.

ALTER TABLE leads
  ADD COLUMN IF NOT EXISTS score INTEGER NOT NULL DEFAULT 0
    CHECK (score >= 0 AND score <= 100);
--> statement-breakpoint
ALTER TABLE leads
  ADD COLUMN IF NOT EXISTS score_updated_at TIMESTAMPTZ;
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS idx_leads_score
  ON leads(tenant_id, score DESC)
  WHERE stage NOT IN ('LOST', 'WON');
--> statement-breakpoint
ALTER TABLE tenant_settings
  ADD COLUMN IF NOT EXISTS lead_scoring_criteria JSONB NOT NULL DEFAULT
    '{"estimated_value_set":10,"high_value":20,"stage_advancement":15,"recent_activity":20,"inbound_source":10,"company_present":5,"phone_present":5,"proposal_viewed":15,"high_value_threshold":20000}'::jsonb;
