WITH schedule_payload AS (
    SELECT
        'Nightly stt_MedicalHistory'::text AS name,
        'daily'::text AS schedule_type,
        TRUE AS enabled,
        FALSE AS catch_up_missed_runs,
        '["stt_MedicalHistory"]'::jsonb AS tables_json,
        TRUE AS send_email,
        FALSE AS dry_run,
        NULL::integer AS read_limit,
        NULL::integer AS interval_seconds,
        '02:00:00'::text AS daily_time,
        NULL::timestamp AS start_at,
        CASE
            WHEN localtime < time '02:00:00'
                THEN date_trunc('day', now()) + time '02:00:00'
            ELSE date_trunc('day', now()) + interval '1 day' + time '02:00:00'
        END AS next_run_at
),
updated AS (
    UPDATE replicator.migration_schedules AS schedules
    SET
        updated_at = now(),
        schedule_type = payload.schedule_type,
        enabled = payload.enabled,
        catch_up_missed_runs = payload.catch_up_missed_runs,
        tables_json = payload.tables_json,
        send_email = payload.send_email,
        dry_run = payload.dry_run,
        read_limit = payload.read_limit,
        interval_seconds = payload.interval_seconds,
        daily_time = payload.daily_time,
        start_at = payload.start_at,
        next_run_at = payload.next_run_at
    FROM schedule_payload AS payload
    WHERE schedules.name = payload.name
    RETURNING schedules.schedule_id
)
INSERT INTO replicator.migration_schedules (
    schedule_id,
    created_at,
    updated_at,
    name,
    schedule_type,
    enabled,
    catch_up_missed_runs,
    tables_json,
    send_email,
    dry_run,
    read_limit,
    interval_seconds,
    daily_time,
    start_at,
    next_run_at
)
SELECT
    md5(random()::text || clock_timestamp()::text),
    now(),
    now(),
    payload.name,
    payload.schedule_type,
    payload.enabled,
    payload.catch_up_missed_runs,
    payload.tables_json,
    payload.send_email,
    payload.dry_run,
    payload.read_limit,
    payload.interval_seconds,
    payload.daily_time,
    payload.start_at,
    payload.next_run_at
FROM schedule_payload AS payload
WHERE NOT EXISTS (SELECT 1 FROM updated);
