-- Migration: Expand cd_rates for multiple market rate types + tenant AI recommendation storage
-- Phase 6: AI Features Part 2

-- 1) Add rate_type column to shared.cd_rates to support CD, Money Market, and High Yield Savings
ALTER TABLE shared.cd_rates
  ADD COLUMN IF NOT EXISTS rate_type VARCHAR(50) DEFAULT 'cd' NOT NULL;

-- Index for filtering by rate type
CREATE INDEX IF NOT EXISTS idx_cd_rates_type ON shared.cd_rates(rate_type);

-- Composite index for getting latest rates by type efficiently
CREATE INDEX IF NOT EXISTS idx_cd_rates_type_fetched ON shared.cd_rates(rate_type, fetched_at DESC);

-- 2) Create ai_recommendations table in each existing tenant schema
-- This stores saved AI investment recommendations per tenant
-- For new tenants, this is handled by tenant-schema.service.ts
DO $$
DECLARE
  tenant_schema TEXT;
BEGIN
  FOR tenant_schema IN
    SELECT schema_name FROM shared.organizations WHERE schema_name IS NOT NULL
  LOOP
    EXECUTE format(
      'CREATE TABLE IF NOT EXISTS %I.ai_recommendations (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        recommendations_json JSONB NOT NULL,
        overall_assessment TEXT,
        risk_notes JSONB,
        requested_by UUID,
        response_time_ms INTEGER,
        created_at TIMESTAMPTZ DEFAULT NOW()
      )', tenant_schema
    );
  END LOOP;
END $$;
