-- Migration: Populate flyer_locations table with existing flyer→store relationships
-- Purpose: The flyer_locations table was created in the initial schema but never populated.
--          This migration populates it with data from the legacy flyer.store_id relationship.
--
-- Background: The schema correctly defines a many-to-many relationship between flyers
--             and store_locations via the flyer_locations table, but all code was using
--             the legacy flyer.store_id foreign key directly.

-- Step 1: For each flyer with a store_id, link it to all locations of that store
-- This assumes that if a flyer is associated with a store, it's valid at ALL locations of that store
INSERT INTO public.flyer_locations (flyer_id, store_location_id)
SELECT DISTINCT
    f.flyer_id,
    sl.store_location_id
FROM public.flyers f
JOIN public.store_locations sl ON f.store_id = sl.store_id
WHERE f.store_id IS NOT NULL
ON CONFLICT (flyer_id, store_location_id) DO NOTHING;

-- Step 2: Add a comment documenting this migration
COMMENT ON TABLE public.flyer_locations IS
'A linking table associating a single flyer with multiple store locations where its deals are valid. Populated from legacy flyer.store_id relationships via migration 004.';

-- Step 3: Verify the migration worked
-- This should return the number of flyer_location entries created
DO $$
DECLARE
    flyer_location_count INTEGER;
    flyer_with_store_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO flyer_location_count FROM public.flyer_locations;
    SELECT COUNT(*) INTO flyer_with_store_count FROM public.flyers WHERE store_id IS NOT NULL;

    RAISE NOTICE 'Migration 004 complete:';
    RAISE NOTICE '  - Created % flyer_location entries', flyer_location_count;
    RAISE NOTICE '  - Based on % flyers with store_id', flyer_with_store_count;

    IF flyer_location_count = 0 AND flyer_with_store_count > 0 THEN
        RAISE EXCEPTION 'Migration 004 failed: No flyer_locations created but flyers with store_id exist';
    END IF;
END $$;

-- Note: The flyer.store_id column is kept for backward compatibility but should eventually be deprecated
-- Future work: Add a migration to remove flyer.store_id once all code uses flyer_locations
