




CREATE TABLE IF NOT EXISTS feed_sources (
    id                INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name              VARCHAR(150) NOT NULL,
    type              ENUM('mrss','rss','csv','json') NOT NULL DEFAULT 'mrss',
    url               TEXT NOT NULL,
    mode              ENUM('embed','download') NOT NULL DEFAULT 'embed',
    enabled           TINYINT(1) NOT NULL DEFAULT 1,
    auto_publish      TINYINT(1) NOT NULL DEFAULT 1,
    video_type        VARCHAR(20) NOT NULL DEFAULT 'straight',
    schedule_interval INT UNSIGNED NOT NULL DEFAULT 0,
    max_pages         SMALLINT UNSIGNED NOT NULL DEFAULT 1,
    page_param        VARCHAR(40) NOT NULL DEFAULT 'page',
    mapping           JSON NULL,
    options           JSON NULL,
    last_run_at       DATETIME NULL,
    last_status       VARCHAR(40) NOT NULL DEFAULT '',
    last_message      VARCHAR(500) NOT NULL DEFAULT '',
    stat_fetched      INT UNSIGNED NOT NULL DEFAULT 0,
    stat_imported     INT UNSIGNED NOT NULL DEFAULT 0,
    stat_skipped      INT UNSIGNED NOT NULL DEFAULT 0,
    stat_failed       INT UNSIGNED NOT NULL DEFAULT 0,
    created_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at        DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_enabled_schedule (enabled, schedule_interval)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS feed_items (
    id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    source_id   INT UNSIGNED NOT NULL,
    guid        VARCHAR(255) NOT NULL,
    title       VARCHAR(500) NOT NULL DEFAULT '',
    payload     JSON NULL,
    status      ENUM('pending','importing','imported','skipped','failed') NOT NULL DEFAULT 'pending',
    video_id    INT UNSIGNED NULL,
    error       VARCHAR(500) NOT NULL DEFAULT '',
    attempts    SMALLINT UNSIGNED NOT NULL DEFAULT 0,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_source_guid (source_id, guid),
    KEY idx_status (status),
    KEY idx_source_status (source_id, status),
    CONSTRAINT fk_feed_items_source FOREIGN KEY (source_id) REFERENCES feed_sources(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
