-- name: CreateScheduledNotification :one
INSERT INTO scheduled_notifications (
    channel, title, message, html,
    scheduled_at,
    target_user_ids, target_role, target_raw,
    created_by
) VALUES (
    $1, $2, $3, $4,
    $5,
    $6, $7, $8,
    $9
)
RETURNING *;

-- name: GetScheduledNotification :one
SELECT * FROM scheduled_notifications
WHERE id = $1;

-- name: ListScheduledNotifications :many
SELECT *
FROM scheduled_notifications
WHERE
    (sqlc.narg('filter_status')::text IS NULL OR status = sqlc.narg('filter_status'))
    AND (sqlc.narg('filter_channel')::text IS NULL OR channel = sqlc.narg('filter_channel'))
    AND (sqlc.narg('filter_after')::timestamptz IS NULL OR scheduled_at >= sqlc.narg('filter_after'))
    AND (sqlc.narg('filter_before')::timestamptz IS NULL OR scheduled_at <= sqlc.narg('filter_before'))
ORDER BY scheduled_at DESC
LIMIT @page_limit OFFSET @page_offset;

-- name: CountScheduledNotifications :one
SELECT COUNT(*)
FROM scheduled_notifications
WHERE
    (sqlc.narg('filter_status')::text IS NULL OR status = sqlc.narg('filter_status'))
    AND (sqlc.narg('filter_channel')::text IS NULL OR channel = sqlc.narg('filter_channel'))
    AND (sqlc.narg('filter_after')::timestamptz IS NULL OR scheduled_at >= sqlc.narg('filter_after'))
    AND (sqlc.narg('filter_before')::timestamptz IS NULL OR scheduled_at <= sqlc.narg('filter_before'));

-- name: CancelScheduledNotification :one
UPDATE scheduled_notifications
SET
    status = 'cancelled',
    cancelled_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
    AND status IN ('pending', 'processing')
RETURNING *;

-- name: ClaimDueScheduledNotifications :many
UPDATE scheduled_notifications sn
SET
    status = 'processing',
    processing_started_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
WHERE sn.id IN (
    SELECT id
    FROM scheduled_notifications
    WHERE status = 'pending'
        AND scheduled_at <= CURRENT_TIMESTAMP
    ORDER BY scheduled_at ASC
    FOR UPDATE SKIP LOCKED
    LIMIT $1
)
RETURNING *;

-- name: MarkScheduledNotificationSent :exec
UPDATE scheduled_notifications
SET
    status = 'sent',
    sent_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1;

-- name: MarkScheduledNotificationFailed :exec
UPDATE scheduled_notifications
SET
    status = 'failed',
    last_error = $2,
    attempt_count = attempt_count + 1,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
