-- 090_scrape_schedules_seed_deactivate_stale_avito.sql
-- Issue #759 — seed scrape_schedules row for nightly deactivation of stale avito listings.
--
-- Context:
--   Avito listings that haven't been seen by the scraper for >AVITO_STALE_TTL_DAYS days
--   (default 10) remain is_active=true indefinitely. This inflates the active-listing
--   denominator used by the coverage and estimator services, degrading accuracy.
--
--   Fix:
--     1. app/tasks/deactivate_stale_avito.py — deactivate_stale_avito_listings()
--        issues a single UPDATE listings SET is_active=false WHERE source='avito'
--        AND is_active=true AND last_seen_at < NOW()-INTERVAL(:ttl_days days).
--        Rows are NOT deleted — history is required for backtest (#667).
--     2. scheduler.py — added trigger_deactivate_stale_avito_run() + dispatch branch
--        `elif source == "deactivate_stale_avito"` in scheduler_loop().
--     3. app/core/config.py — AVITO_STALE_TTL_DAYS setting (default 10).
--     4. This migration — seeds the scrape_schedules row.
--
-- Schedule window 06:00-07:00 UTC:
--   After the avito_city_sweep window (02:00-05:00 UTC per #814). Running after the
--   sweep ensures listings genuinely seen in the nightly pass are NOT deactivated.
--
-- next_run_at bootstrapped to tomorrow 06:00 UTC so the scheduler does not fire
-- immediately on deploy (same pattern as 079/082/088).
--
-- Idempotent: ON CONFLICT (source) DO NOTHING — safe to re-apply.
--
-- Dependencies:
--   052_scrape_schedules.sql (table + UNIQUE(source)).
--   listings table with last_seen_at column (002_core_tables.sql).
--   scheduler.py change (trigger_deactivate_stale_avito_run must be deployed).
--
-- Deploy order:
--   Apply this migration after deploying the scheduler.py + task changes 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
(
    'deactivate_stale_avito',
    true,                                        -- SAFE: pure internal DB UPDATE, no ext calls
    6,
    7,
    ((CURRENT_DATE + INTERVAL '1 day') + make_interval(hours => 6)) 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), '
    'deactivate_stale_avito (#759).';

COMMIT;
