-- Migration 020: Add grouped daily market data source and allow
-- global (non-company-specific) sources and market snapshots.

-- Allow market_snapshots to store bars for tickers not in our companies table
ALTER TABLE market_snapshots ALTER COLUMN company_id DROP NOT NULL;

-- Allow sources to exist without a company (for global market data sources)
ALTER TABLE sources DROP CONSTRAINT sources_company_id_fkey;
ALTER TABLE sources ALTER COLUMN company_id DROP NOT NULL;
ALTER TABLE sources ADD CONSTRAINT sources_company_id_fkey
    FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE;

-- Add the grouped daily source (fetches ALL US stock bars in one API call)
INSERT INTO sources (source_type, source_name, config, active, company_id)
SELECT
    'market_api',
    'Polygon Grouped Daily',
    '{"endpoint": "grouped_daily", "provider": "polygon", "adjusted": true}'::jsonb,
    true,
    NULL
WHERE NOT EXISTS (
    SELECT 1 FROM sources
    WHERE source_type = 'market_api'
      AND config->>'endpoint' = 'grouped_daily'
);
