-- name: CreateWorktree :one
INSERT INTO workspace_worktrees (
  id, workspace_id, branch, path, status, active_holder, acquired_at
) VALUES ($1,$2,$3,$4,$5,$6,$7)
RETURNING *;

-- name: GetWorktreeByID :one
SELECT * FROM workspace_worktrees WHERE id = $1;

-- name: GetWorktreeByIDForUpdate :one
SELECT * FROM workspace_worktrees WHERE id = $1
FOR UPDATE;

-- name: GetWorktreeByBranchForUpdate :one
SELECT * FROM workspace_worktrees
WHERE workspace_id = $1 AND branch = $2
FOR UPDATE;

-- name: ListWorktreesByWorkspace :many
SELECT * FROM workspace_worktrees
WHERE workspace_id = $1
ORDER BY created_at DESC;

-- name: SetWorktreeActive :one
UPDATE workspace_worktrees
SET status = 'active',
    active_holder = $2,
    acquired_at = now(),
    last_used_at = now(),
    prune_warning_at = NULL
WHERE id = $1
RETURNING *;

-- name: SetWorktreeIdle :one
UPDATE workspace_worktrees
SET status = 'idle',
    active_holder = NULL,
    acquired_at = NULL,
    last_used_at = now(),
    prune_warning_at = NULL
WHERE id = $1
RETURNING *;

-- name: SetWorktreePruning :one
UPDATE workspace_worktrees
SET status = 'pruning', last_used_at = now()
WHERE id = $1
RETURNING *;

-- name: DeleteWorktree :exec
DELETE FROM workspace_worktrees WHERE id = $1;

-- name: ListWorktreesNeedingPruneWarning :many
SELECT * FROM workspace_worktrees
 WHERE status = 'idle'
   AND prune_warning_at IS NULL
   AND last_used_at < $1
 ORDER BY last_used_at ASC;

-- name: ListWorktreesNeedingPrune :many
SELECT * FROM workspace_worktrees
 WHERE status = 'idle'
   AND last_used_at < $1
 ORDER BY last_used_at ASC;

-- name: MarkPruneWarning :exec
UPDATE workspace_worktrees
   SET prune_warning_at = now()
 WHERE id = $1 AND prune_warning_at IS NULL;

-- name: TryStartPrune :one
UPDATE workspace_worktrees
   SET status = 'pruning'
 WHERE id = $1 AND status = 'idle'
RETURNING *;

-- name: FinishPruneSuccess :exec
DELETE FROM workspace_worktrees WHERE id = $1;

-- name: FinishPruneRollback :exec
UPDATE workspace_worktrees
   SET status = 'idle'
 WHERE id = $1 AND status = 'pruning';

-- name: ReleaseWorktreesByHolder :many
UPDATE workspace_worktrees
SET status = 'idle',
    active_holder = NULL,
    acquired_at = NULL,
    last_used_at = now(),
    prune_warning_at = NULL
WHERE active_holder = $1 AND status = 'active'
RETURNING *;
