CREATE TABLE hosts (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    hostname      TEXT NOT NULL UNIQUE,
    mac           TEXT NOT NULL UNIQUE,
    server_type   TEXT NOT NULL,
    state         TEXT NOT NULL DEFAULT 'registered',
    ip_address    TEXT,
    hardware_id   TEXT,
    infra_host_id INTEGER,
    notes         TEXT NOT NULL DEFAULT '',
    created_at    TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
    updated_at    TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);

CREATE TABLE operations (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    host_id       INTEGER NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
    kind          TEXT NOT NULL,
    state         TEXT NOT NULL DEFAULT 'active',
    image_id      INTEGER REFERENCES images(id),
    started_at    TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
    completed_at  TEXT,
    error_message TEXT
);
CREATE INDEX idx_operations_host ON operations(host_id);

CREATE TABLE operation_locks (
    host_id       INTEGER PRIMARY KEY REFERENCES hosts(id) ON DELETE CASCADE,
    operation_id  INTEGER NOT NULL REFERENCES operations(id),
    locked_at     TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
    expires_at    TEXT NOT NULL
);

CREATE TABLE images (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    name          TEXT NOT NULL UNIQUE,
    kind          TEXT NOT NULL,
    version       TEXT NOT NULL,
    kernel_path   TEXT NOT NULL,
    initrd_path   TEXT NOT NULL,
    is_default    INTEGER NOT NULL DEFAULT 0,
    created_at    TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);
