-- name: ListWorkspaceSlotsByProject :many
SELECT id, project_sync_setting_id, slot_index, state, path, created_at, updated_at
FROM workspace_slots
WHERE project_sync_setting_id = $1
ORDER BY slot_index;

-- name: UpsertWorkspaceSlot :one
INSERT INTO workspace_slots (project_sync_setting_id, slot_index, state, path)
VALUES ($1, $2, 'available', $3)
ON CONFLICT (project_sync_setting_id, slot_index)
DO UPDATE SET path = EXCLUDED.path, updated_at = now()
RETURNING id, project_sync_setting_id, slot_index, state, path, created_at, updated_at;

-- name: ReserveAvailableWorkspaceSlot :one
UPDATE workspace_slots
SET state = 'in_use', updated_at = now()
WHERE id = (
    SELECT ws.id FROM workspace_slots ws
    WHERE ws.project_sync_setting_id = $1 AND ws.state = 'available'
    ORDER BY ws.slot_index
    LIMIT 1
    FOR UPDATE SKIP LOCKED
)
RETURNING id, project_sync_setting_id, slot_index, state, path, created_at, updated_at;

-- name: UpdateWorkspaceSlotState :one
UPDATE workspace_slots
SET state = $2, updated_at = now()
WHERE id = $1
RETURNING id, project_sync_setting_id, slot_index, state, path, created_at, updated_at;
