-- Migration: Create checkouts table for sidecar development flow
-- Tracks checkout sessions where users clone repos locally with temporary tokens

CREATE TABLE IF NOT EXISTS checkouts (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id       TEXT NOT NULL,
    branch           VARCHAR(255) NOT NULL,
    feature_slug     VARCHAR(255),
    gitea_token_id   BIGINT NOT NULL,
    gitea_token_name VARCHAR(255) NOT NULL,
    clone_url        TEXT NOT NULL,
    checked_out_by   VARCHAR(255) NOT NULL,
    checked_out_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at       TIMESTAMPTZ NOT NULL,
    status           VARCHAR(20) NOT NULL DEFAULT 'active',
    checked_in_at    TIMESTAMPTZ,
    review_task_id   TEXT,

    CONSTRAINT checkouts_status_check CHECK (status IN ('active', 'checked_in', 'expired', 'revoked'))
);

-- Unique constraint: only one active checkout per project+branch
-- This prevents conflicts when multiple users try to checkout the same branch
CREATE UNIQUE INDEX idx_checkouts_active_branch
    ON checkouts(project_id, branch)
    WHERE status = 'active';

-- Index for cleanup job to find expired checkouts efficiently
CREATE INDEX idx_checkouts_expires
    ON checkouts(expires_at)
    WHERE status = 'active';

-- Index for listing checkouts by user
CREATE INDEX idx_checkouts_user
    ON checkouts(checked_out_by, status);

-- Index for listing checkouts by project
CREATE INDEX idx_checkouts_project
    ON checkouts(project_id, checked_out_at DESC);
