-- Migration: 003_auto_update.sql
-- Purpose: Add auto-update infrastructure (releases table and machine version tracking)

-- ============================================================================
-- Releases Table
-- ============================================================================

-- Track available agent releases
CREATE TABLE IF NOT EXISTS releases (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    version VARCHAR(32) NOT NULL UNIQUE,
    download_url TEXT NOT NULL,
    checksum_sha256 VARCHAR(64) NOT NULL,
    release_notes TEXT,
    is_stable BOOLEAN NOT NULL DEFAULT false,
    is_mandatory BOOLEAN NOT NULL DEFAULT false,
    min_version VARCHAR(32),              -- Minimum version that can update to this
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Index for finding latest stable release
CREATE INDEX IF NOT EXISTS idx_releases_stable ON releases(is_stable, created_at DESC);

-- ============================================================================
-- Machine Version Tracking
-- ============================================================================

-- Add version tracking columns to existing machines table
ALTER TABLE connect_machines ADD COLUMN IF NOT EXISTS agent_version VARCHAR(32);
ALTER TABLE connect_machines ADD COLUMN IF NOT EXISTS update_status VARCHAR(32);
ALTER TABLE connect_machines ADD COLUMN IF NOT EXISTS last_update_check TIMESTAMPTZ;

-- Index for finding machines needing updates
CREATE INDEX IF NOT EXISTS idx_machines_version ON connect_machines(agent_version);
CREATE INDEX IF NOT EXISTS idx_machines_update_status ON connect_machines(update_status);
