-- Migration 012: Builds table for CI/CD tracking
-- Purpose: Track builds and link them to sessions and versions
-- Dependencies: 001_base_schema.sql (versions table), 010_sessions.sql (sessions table)

-- Builds table: Store build information linked to sessions and versions
CREATE TABLE IF NOT EXISTS builds (
    id SERIAL PRIMARY KEY,
    session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,
    version_id TEXT REFERENCES versions(id) ON DELETE CASCADE,

    build_number INTEGER NOT NULL,
    status TEXT DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'success', 'failed')),

    -- Build metadata
    git_commit_sha TEXT,
    git_branch TEXT,
    build_log_url TEXT,
    artifacts_url TEXT,

    -- Timing
    started_at TIMESTAMP WITH TIME ZONE NOT NULL,
    finished_at TIMESTAMP WITH TIME ZONE,
    duration_seconds INTEGER GENERATED ALWAYS AS
        (EXTRACT(EPOCH FROM (finished_at - started_at))) STORED,

    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for efficient querying
CREATE INDEX idx_builds_session ON builds(session_id);
CREATE INDEX idx_builds_version ON builds(version_id);
CREATE INDEX idx_builds_status ON builds(status);
CREATE INDEX idx_builds_started ON builds(started_at DESC);
CREATE INDEX idx_builds_commit ON builds(git_commit_sha);

-- Unique constraint: one build number per version
CREATE UNIQUE INDEX idx_builds_version_number ON builds(version_id, build_number)
    WHERE version_id IS NOT NULL;

-- Comments for documentation
COMMENT ON TABLE builds IS 'CI/CD build tracking linked to sessions and versions';
COMMENT ON COLUMN builds.session_id IS 'Optional link to session that triggered the build';
COMMENT ON COLUMN builds.version_id IS 'Link to version being built';
COMMENT ON COLUMN builds.duration_seconds IS 'Auto-calculated build duration in seconds';
COMMENT ON COLUMN builds.build_log_url IS 'URL to build logs (e.g., GitHub Actions run)';
COMMENT ON COLUMN builds.artifacts_url IS 'URL to build artifacts (e.g., app binary, Docker image)';
