-- 023_ResyncFiscalYearsToLedger.sql
-- Re-syncs all fiscal years that are missing from accounting_periods.
-- This fixes periods that failed to sync due to the unique constraint on name
-- (which was removed in migration 022).

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

        -- Insert any missing fiscal years
        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-%'
          AND uuid(substring(aggregate_id from 12))::uuid NOT IN (SELECT id FROM accounting_periods)
        ON CONFLICT (id) DO NOTHING;
    END IF;
END $$;
