CREATE TABLE IF NOT EXISTS healthchecks (
    id              TEXT    PRIMARY KEY,
    site_key        TEXT    NOT NULL,
    started_at      INTEGER NOT NULL,
    finished_at     INTEGER NULL,
    technician_id   INTEGER NULL,
    reporting_url   TEXT    NOT NULL,
    wp_version      TEXT    NULL,
    php_version     TEXT    NULL,
    created_at      INTEGER NOT NULL,
    updated_at      INTEGER NOT NULL,
    UNIQUE (site_key, started_at)
);

CREATE INDEX IF NOT EXISTS healthchecks_site_started_idx
    ON healthchecks (site_key, started_at DESC);

CREATE INDEX IF NOT EXISTS healthchecks_site_finished_idx
    ON healthchecks (site_key, finished_at);

CREATE TABLE IF NOT EXISTS step_updates (
    healthcheck_id  TEXT    NOT NULL REFERENCES healthchecks(id) ON DELETE CASCADE,
    step_id         TEXT    NOT NULL,
    status          TEXT    NOT NULL,
    notes           TEXT    NOT NULL DEFAULT '',
    autocheck_json  TEXT    NULL,
    reporting_url   TEXT    NOT NULL,
    updated_at      INTEGER NOT NULL,
    PRIMARY KEY (healthcheck_id, step_id)
);

CREATE INDEX IF NOT EXISTS step_updates_step_updated_idx
    ON step_updates (step_id, updated_at DESC);

CREATE TABLE IF NOT EXISTS request_log (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    ts         INTEGER NOT NULL,
    method     TEXT    NOT NULL,
    path       TEXT    NOT NULL,
    status     INTEGER NOT NULL,
    ip         TEXT    NULL,
    bytes_in   INTEGER NULL,
    bytes_out  INTEGER NULL
);

CREATE INDEX IF NOT EXISTS request_log_ts_idx ON request_log (ts DESC);
