-- AtlasOS - Calypso
-- Migration 015: Add Bacula clients and capability history tables
--
-- Adds tables for tracking registered Bacula agents, their backup capabilities,
-- and a history log for UI- or agent-triggered capability changes. Pending
-- updates are stored on the client row until the agent pulls them.

CREATE TABLE IF NOT EXISTS bacula_clients (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    hostname TEXT NOT NULL,
    ip_address TEXT,
    agent_version TEXT,
    status TEXT NOT NULL DEFAULT 'online',
    backup_types JSONB NOT NULL,
    pending_backup_types JSONB,
    pending_requested_by UUID,
    pending_requested_at TIMESTAMPTZ,
    pending_notes TEXT,
    metadata JSONB,
    registered_by_user_id UUID NOT NULL,
    last_seen TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uniq_bacula_clients_hostname UNIQUE (hostname)
);

CREATE INDEX IF NOT EXISTS idx_bacula_clients_registered_by ON bacula_clients (registered_by_user_id);
CREATE INDEX IF NOT EXISTS idx_bacula_clients_status ON bacula_clients (status);

CREATE TABLE IF NOT EXISTS bacula_client_capability_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    client_id UUID NOT NULL REFERENCES bacula_clients (id) ON DELETE CASCADE,
    backup_types JSONB NOT NULL,
    source TEXT NOT NULL,
    requested_by_user_id UUID,
    requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    notes TEXT
);

CREATE INDEX IF NOT EXISTS idx_bacula_client_capability_history_client ON bacula_client_capability_history (client_id);
CREATE INDEX IF NOT EXISTS idx_bacula_client_capability_history_requested_at ON bacula_client_capability_history (requested_at);

COMMENT ON TABLE bacula_clients IS 'Tracks Bacula clients registered with Calypso, including pending capability pushes.';
COMMENT ON TABLE bacula_client_capability_history IS 'Audit history of backup capability changes per client.';
