-- Migration: Remove sync_completed_at column from stores table
-- This consolidates sync timing to use store_sync_config.last_sync_at as single source of truth

-- First, migrate any existing sync_completed_at data to store_sync_config.last_sync_at
-- This ensures no data is lost during the migration
UPDATE store_sync_config
SET last_sync_at = stores.sync_completed_at
FROM stores
WHERE store_sync_config.store_id = stores.id
  AND stores.sync_completed_at IS NOT NULL
  AND (store_sync_config.last_sync_at IS NULL 
       OR stores.sync_completed_at > store_sync_config.last_sync_at);

-- Drop the sync_completed_at column from stores table
ALTER TABLE stores DROP COLUMN IF EXISTS sync_completed_at;

-- Add comment explaining the change
COMMENT ON TABLE store_sync_config IS 'Store sync configuration and timing. The last_sync_at field is the single source of truth for when a sync last completed.';
COMMENT ON COLUMN store_sync_config.last_sync_at IS 'Single source of truth for last sync completion time. Used by both Web UI display and scheduling logic.';
COMMENT ON COLUMN stores.sync_status IS 'Runtime sync status (idle, syncing, completed, error). Does not include timing - see store_sync_config.last_sync_at for that.';
