-- 001: schema inicial de services_api operations.db (issue 0106)
-- Estado actual + transitions append-only.

CREATE TABLE IF NOT EXISTS service_state (
    app_id              TEXT NOT NULL,
    pc_id               TEXT NOT NULL,
    systemd_state       TEXT NOT NULL DEFAULT '',  -- active|inactive|failed|unknown|no-route
    port_listening      INTEGER NOT NULL DEFAULT 0,
    http_status         INTEGER NOT NULL DEFAULT 0,
    http_latency_ms     INTEGER NOT NULL DEFAULT 0,
    last_check_ts       INTEGER NOT NULL DEFAULT 0,
    last_change_ts      INTEGER NOT NULL DEFAULT 0,
    last_error          TEXT NOT NULL DEFAULT '',
    overall             TEXT NOT NULL DEFAULT 'unknown',  -- ok|degraded|down|no-route|unknown
    PRIMARY KEY (app_id, pc_id)
);

CREATE TABLE IF NOT EXISTS service_transition (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    ts          INTEGER NOT NULL,
    app_id      TEXT NOT NULL,
    pc_id       TEXT NOT NULL,
    from_state  TEXT NOT NULL,
    to_state    TEXT NOT NULL,
    detail      TEXT NOT NULL DEFAULT ''
);

CREATE INDEX IF NOT EXISTS idx_transition_app_pc_ts
    ON service_transition(app_id, pc_id, ts DESC);
