-- 010_SyncFiscalYearsToLedger.sql
-- Syncs existing fiscal years from Books.Api to Ledger's accounting_periods table.
-- Required because the LedgerPeriodSyncSubscriber was added after fiscal years were created.

-- Only run if both tables exist (Ledger schema must be set up first)
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'accounting_periods')
       AND EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'fiscal_year_read_models') THEN

        -- Extract GUID from aggregate_id (format: "fiscalyear-{guid}")
        INSERT INTO accounting_periods (id, name, start_date, end_date, is_locked, created_at)
        SELECT
            uuid(substring(aggregate_id from 12))::uuid as id,
            name,
            start_date,
            end_date,
            (status = 'locked') as is_locked,
            create_time as created_at
        FROM fiscal_year_read_models
        WHERE aggregate_id LIKE 'fiscalyear-%'
        ON CONFLICT (id) DO UPDATE SET
            name = EXCLUDED.name,
            start_date = EXCLUDED.start_date,
            end_date = EXCLUDED.end_date,
            is_locked = EXCLUDED.is_locked;
    END IF;
END $$;
