-- 088_scrape_schedules_seed_search_matview_refresh.sql
-- Issue #769 Part C (finding #14) — seed scrape_schedules row for daily
-- listings_search_mv materialized view refresh.
--
-- Context:
--   listings_search_mv (created in 050_search_optimization.sql) is actively read by
--   search_query.py (SELECT FROM listings_search_mv) for the /api/v1/search endpoint.
--   The refresh callable (app/tasks/refresh_search_matview.py) exists but was NEVER
--   wired into the in-app scheduler: no scrape_schedules row, no dispatch branch in
--   scheduler_loop(). Without a scheduled refresh the matview becomes stale after the
--   initial CREATE MATERIALIZED VIEW population.
--
--   Fix:
--     1. scheduler.py — added trigger_refresh_search_matview_run() + dispatch branch
--        `elif source == "refresh_search_matview"` in scheduler_loop().
--     2. This migration — seeds the scrape_schedules row (enabled=true, 03:00-04:00 UTC).
--
-- Schedule window 03:00-04:00 UTC:
--   Nightly, before rosreestr_dkp_import (04:00-06:00 UTC). Refresh takes <10s on a
--   non-empty matview (CONCURRENTLY — readers are not blocked).
--
-- next_run_at bootstrapped to tomorrow 03:00 UTC so the scheduler does not fire
-- immediately on deploy (same pattern as 078/079/082).
--
-- Idempotent: ON CONFLICT (source) DO NOTHING — safe to re-apply.
--
-- Dependencies:
--   052_scrape_schedules.sql (table + UNIQUE(source)).
--   050_search_optimization.sql (listings_search_mv must exist in DB).
--   scheduler.py change (trigger_refresh_search_matview_run must be deployed).
--
-- Deploy order:
--   Apply this migration after deploying the scheduler.py change so the scheduler
--   can dispatch the new source name correctly on first fire.

BEGIN;

INSERT INTO scrape_schedules (
    source,
    enabled,
    window_start_hour,
    window_end_hour,
    next_run_at,
    default_params
)
VALUES
(
    'refresh_search_matview',
    true,                                        -- SAFE: pure internal DB, REFRESH CONCURRENTLY
    3,
    4,
    ((CURRENT_DATE + INTERVAL '1 day') + make_interval(hours => 3)) AT TIME ZONE 'UTC',
    '{}'::jsonb
)
ON CONFLICT (source) DO NOTHING;

COMMENT ON TABLE scrape_schedules IS
    'In-app scheduler config (заменяет cron-script setup). '
    'Sources: avito_city_sweep, yandex_city_sweep (dormant, #561), '
    'cian_history_backfill, rosreestr_dkp_import, listing_source_snapshot (#570), '
    'asking_to_sold_ratio_refresh (#648), refresh_search_matview (#769).';

COMMIT;
