from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration


def create_job_runs(connection: sqlite3.Connection) -> None:
    connection.execute(
        """
        CREATE TABLE IF NOT EXISTS job_runs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            job_id TEXT NOT NULL,
            idempotency_key TEXT NOT NULL,
            status TEXT NOT NULL,
            attempt INTEGER NOT NULL DEFAULT 1,
            started_at TEXT NOT NULL,
            finished_at TEXT,
            elapsed_ms INTEGER NOT NULL DEFAULT 0,
            error_code TEXT NOT NULL DEFAULT '',
            message TEXT NOT NULL DEFAULT '',
            output_version TEXT NOT NULL DEFAULT '',
            metadata TEXT NOT NULL DEFAULT '{}',
            UNIQUE(job_id, idempotency_key, attempt)
        )
        """
    )
    connection.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_job_runs_job_started
        ON job_runs(job_id, started_at DESC, id DESC)
        """
    )
    connection.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_job_runs_status
        ON job_runs(status, started_at DESC, id DESC)
        """
    )


MIGRATION = Migration(
    version="0002",
    name="create_job_runs",
    action=create_job_runs,
    signature="job-runs:v1:id,job,key,status,attempt,times,elapsed,error,output,metadata",
)
