-- Portable across SQLite and MySQL 8.0+:
--   - VARCHAR(N) is honoured by MySQL, treated as TEXT by SQLite.
--   - BIGINT covers post-2038 unix seconds; SQLite stores as INTEGER affinity.
--   - No AUTO_INCREMENT in this file — we don't need it for the current tables.
--     (An audit table that needs an autoincrement id can come in a later
--     migration with per-driver dispatch in Migrations.php.)
--
-- Re-running is safe: Migrations.php only applies each .sql file once
-- (tracked in the `migrations` table created in PHP).

CREATE TABLE IF NOT EXISTS healthchecks (
    id              VARCHAR(64)  NOT NULL,
    site_key        VARCHAR(255) NOT NULL,
    started_at      BIGINT       NOT NULL,
    finished_at     BIGINT       NULL,
    technician_id   BIGINT       NULL,
    reporting_url   VARCHAR(512) NOT NULL,
    wp_version      VARCHAR(32)  NULL,
    php_version     VARCHAR(32)  NULL,
    created_at      BIGINT       NOT NULL,
    updated_at      BIGINT       NOT NULL,
    PRIMARY KEY (id),
    UNIQUE (site_key, started_at)
);

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

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

CREATE TABLE IF NOT EXISTS step_updates (
    healthcheck_id  VARCHAR(64)  NOT NULL,
    step_id         VARCHAR(64)  NOT NULL,
    status          VARCHAR(32)  NOT NULL,
    notes           TEXT         NOT NULL,
    autocheck_json  TEXT         NULL,
    reporting_url   VARCHAR(512) NOT NULL,
    updated_at      BIGINT       NOT NULL,
    PRIMARY KEY (healthcheck_id, step_id),
    CONSTRAINT fk_step_updates_hc FOREIGN KEY (healthcheck_id)
        REFERENCES healthchecks(id) ON DELETE CASCADE
);

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