-- Migration: Add health_scores table to all tenant schemas
-- This table stores AI-derived operating and reserve fund health scores

DO $$
DECLARE
  tenant RECORD;
BEGIN
  FOR tenant IN
    SELECT schema_name FROM shared.organizations WHERE status = 'active'
  LOOP
    EXECUTE format(
      'CREATE TABLE IF NOT EXISTS %I.health_scores (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        score_type VARCHAR(20) NOT NULL CHECK (score_type IN (''operating'', ''reserve'')),
        score INTEGER NOT NULL CHECK (score >= 0 AND score <= 100),
        previous_score INTEGER,
        trajectory VARCHAR(20) CHECK (trajectory IN (''improving'', ''stable'', ''declining'')),
        label VARCHAR(30),
        summary TEXT,
        factors JSONB,
        recommendations JSONB,
        missing_data JSONB,
        status VARCHAR(20) NOT NULL DEFAULT ''complete'' CHECK (status IN (''complete'', ''pending'', ''error'')),
        response_time_ms INTEGER,
        calculated_at TIMESTAMPTZ DEFAULT NOW(),
        created_at TIMESTAMPTZ DEFAULT NOW()
      )', tenant.schema_name
    );
    EXECUTE format(
      'CREATE INDEX IF NOT EXISTS idx_%s_hs_type_calc ON %I.health_scores(score_type, calculated_at DESC)',
      replace(tenant.schema_name, '.', '_'), tenant.schema_name
    );
  END LOOP;
END $$;
