-- name: CreateTeamInvitation :one
INSERT INTO team_invitations (
    team_member_id,
    token,
    status,
    expires_at,
    invited_by,
    updated_at
)
VALUES ($1, $2, 'pending', $3, $4, CURRENT_TIMESTAMP)
RETURNING *;

-- name: GetTeamInvitationByToken :one
SELECT * FROM team_invitations
WHERE token = $1;

-- name: GetTeamInvitationByID :one
SELECT * FROM team_invitations
WHERE id = $1;

-- name: GetPendingTeamInvitationByMemberID :one
SELECT * FROM team_invitations
WHERE team_member_id = $1
  AND status = 'pending'
ORDER BY created_at DESC
LIMIT 1;

-- name: RevokePendingTeamInvitationsForMember :exec
UPDATE team_invitations
SET status = 'revoked',
    updated_at = CURRENT_TIMESTAMP
WHERE team_member_id = $1
  AND status = 'pending';

-- name: AcceptTeamInvitation :one
UPDATE team_invitations
SET status = 'accepted',
    accepted_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
  AND status = 'pending'
RETURNING *;

-- name: RevokeTeamInvitation :one
UPDATE team_invitations
SET status = 'revoked',
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
  AND status = 'pending'
RETURNING *;

-- name: ExpireTeamInvitation :exec
UPDATE team_invitations
SET status = 'expired',
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
  AND status = 'pending';

-- name: ListTeamInvitations :many
SELECT
    ti.id,
    ti.team_member_id,
    ti.token,
    ti.status,
    ti.expires_at,
    ti.invited_by,
    ti.accepted_at,
    ti.created_at,
    ti.updated_at,
    tm.email,
    tm.first_name,
    tm.last_name,
    tm.team_role,
    COUNT(*) OVER () AS total_count
FROM team_invitations ti
INNER JOIN team_members tm ON tm.id = ti.team_member_id
WHERE (sqlc.narg('status')::text IS NULL OR ti.status = sqlc.narg('status')::text)
ORDER BY ti.created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;
