-- 115_scrape_schedules_seed_deactivate_stale_yandex_cian.sql
-- Seed scrape_schedules rows for nightly segment-aware stale-listing deactivation
-- of yandex and cian vtorichka (#759 generalisation).
--
-- Rationale (segment-aware vs blanket TTL):
--   Yandex and Cian city sweeps do NOT maintain full inventory coverage -- they
--   sample a rolling window rather than crawling every live listing on every run.
--   A blanket TTL (as used for Avito) would therefore wrongly deactivate live
--   novostroyki and unknown-segment (NULL) rows that simply were not re-visited
--   in the sample window.
--
--   DECISION (user-approved): deactivate ONLY listing_segment='vtorichka' rows,
--   with TTL=30 days.  This is conservative enough that at first deploy it will
--   touch 0 rows (no vtorichka listing has been absent for 30 days yet), but will
--   catch genuinely-stale secondhand inventory going forward.
--
--   novostroyki rows (9659 active first-party rows as of 2026-06-16) are protected:
--   they are managed by dedicated newbuilding pipelines and must not be deactivated
--   by this task.  NULL-segment rows are also excluded as their segment is unknown.
--
-- Schedule window 07:00-08:00 UTC:
--   After avito deactivate_stale (06:00-07:00 UTC) and after the main city sweeps
--   (02:00-05:00 UTC) and Rosreestr OS-cron (05:30/05:45 UTC).
--   Pattern: next_run_at bootstrapped to tomorrow 07:00 UTC so the scheduler does
--   not fire immediately on deploy.
--
-- Idempotent: ON CONFLICT (source) DO NOTHING -- safe to re-apply.
--
-- Dependencies:
--   052_scrape_schedules.sql (table + UNIQUE(source)).
--   listings table with listing_segment column.
--   app/tasks/deactivate_stale_avito.py -- deactivate_stale_listings() (generic fn).
--   app/services/scheduler.py -- trigger_deactivate_stale_run() + dispatch branch
--     source.startswith("deactivate_stale_").
--
-- Deploy order:
--   Apply after deploying the scheduler.py + task changes.

BEGIN;

INSERT INTO scrape_schedules (
    source,
    enabled,
    window_start_hour,
    window_end_hour,
    next_run_at,
    default_params
)
VALUES
(
    'deactivate_stale_yandex',
    true,
    7,
    8,
    ((CURRENT_DATE + INTERVAL '1 day') + make_interval(hours => 7)) AT TIME ZONE 'UTC',
    '{"listing_source":"yandex","ttl_days":30,"segments":["vtorichka"]}'::jsonb
),
(
    'deactivate_stale_cian',
    true,
    7,
    8,
    ((CURRENT_DATE + INTERVAL '1 day') + make_interval(hours => 7)) AT TIME ZONE 'UTC',
    '{"listing_source":"cian","ttl_days":30,"segments":["vtorichka"]}'::jsonb
)
ON CONFLICT (source) DO NOTHING;

COMMIT;
