-- v0.21.4: Git integration — credentials table + workspace git columns.

-- Git credentials: encrypted storage for PAT, basic auth, and SSH keys.
-- Uses the same AES-256-GCM vault pattern as BYOK provider configs.
CREATE TABLE IF NOT EXISTS git_credentials (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name        TEXT NOT NULL DEFAULT '',
    auth_type   TEXT NOT NULL DEFAULT 'https_pat',  -- https_pat, https_basic, ssh_key
    encrypted_data BYTEA NOT NULL DEFAULT '',
    nonce       BYTEA NOT NULL DEFAULT '',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_git_credentials_user ON git_credentials(user_id);

-- Workspace git tracking columns.
ALTER TABLE workspaces ADD COLUMN IF NOT EXISTS git_remote_url    TEXT;
ALTER TABLE workspaces ADD COLUMN IF NOT EXISTS git_branch        TEXT;
ALTER TABLE workspaces ADD COLUMN IF NOT EXISTS git_credential_id UUID REFERENCES git_credentials(id) ON DELETE SET NULL;
ALTER TABLE workspaces ADD COLUMN IF NOT EXISTS git_last_sync     TIMESTAMPTZ;
