-- Migration: Create sessions table for interactive remote development
-- Sessions compose checkout (git token) + pod binding + ephemeral preview URL

CREATE TABLE IF NOT EXISTS sessions (
    id             UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id     TEXT NOT NULL,
    checkout_id    UUID NOT NULL REFERENCES checkouts(id),
    pod_name       VARCHAR(255) NOT NULL,
    preview_url    TEXT NOT NULL,
    preview_host   VARCHAR(255) NOT NULL,
    created_by     VARCHAR(255) NOT NULL,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at     TIMESTAMPTZ NOT NULL,
    status         VARCHAR(20) NOT NULL DEFAULT 'active',
    ended_at       TIMESTAMPTZ,

    CONSTRAINT sessions_status_check CHECK (status IN ('active', 'ended', 'expired'))
);

-- Only one active session per project at a time
CREATE UNIQUE INDEX idx_sessions_active_project
    ON sessions(project_id) WHERE status = 'active';

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

-- Index for listing sessions by project
CREATE INDEX idx_sessions_project
    ON sessions(project_id, created_at DESC);

-- Index for looking up session by checkout
CREATE INDEX idx_sessions_checkout
    ON sessions(checkout_id);
