-- name: InsertPermissionRequest :one
INSERT INTO acp_permission_requests (
  id, session_id, agent_request_id, tool_name, tool_call, options, status, chosen_option_id, decided_by, decided_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id, session_id, agent_request_id, tool_name, tool_call, options, status,
          chosen_option_id, decided_by, decided_at, created_at;

-- name: GetPermissionRequestByID :one
SELECT id, session_id, agent_request_id, tool_name, tool_call, options, status,
       chosen_option_id, decided_by, decided_at, created_at
FROM acp_permission_requests
WHERE id = $1;

-- name: ListPendingPermissionRequestsBySession :many
SELECT id, session_id, agent_request_id, tool_name, tool_call, options, status,
       chosen_option_id, decided_by, decided_at, created_at
FROM acp_permission_requests
WHERE session_id = $1 AND status = 'pending'
ORDER BY created_at ASC;

-- name: ListPendingPermissionRequestsByUser :many
SELECT p.id, p.session_id, p.agent_request_id, p.tool_name, p.tool_call, p.options, p.status,
       p.chosen_option_id, p.decided_by, p.decided_at, p.created_at
FROM acp_permission_requests p
JOIN acp_sessions s ON s.id = p.session_id
WHERE s.user_id = $1 AND p.status = 'pending'
ORDER BY p.created_at ASC;

-- name: DecidePermissionRequest :one
UPDATE acp_permission_requests
SET status = $2, chosen_option_id = $3, decided_by = $4, decided_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING id, session_id, agent_request_id, tool_name, tool_call, options, status,
          chosen_option_id, decided_by, decided_at, created_at;

-- name: ExpirePendingPermissionRequestsBySession :execrows
UPDATE acp_permission_requests
SET status = 'expired', decided_at = now()
WHERE session_id = $1 AND status = 'pending';

-- name: ExpireStalePermissionRequests :execrows
UPDATE acp_permission_requests
SET status = 'expired', decided_at = now()
WHERE status = 'pending' AND created_at < $1;
