-- name: CreateCalendarSubscription :one
INSERT INTO calendar_subscriptions (id, calendar_id, source_url, sync_interval_minutes)
VALUES ($1, $2, $3, $4)
RETURNING *;

-- name: ListSubscriptionsByCalendar :many
SELECT * FROM calendar_subscriptions
WHERE calendar_id = $1
ORDER BY created_at ASC;

-- name: GetSubscriptionByID :one
SELECT * FROM calendar_subscriptions
WHERE id = $1;

-- name: DeleteSubscription :exec
DELETE FROM calendar_subscriptions
WHERE id = $1;

-- name: UpdateSubscriptionLastSynced :exec
UPDATE calendar_subscriptions
SET last_synced_at = now()
WHERE id = $1;

-- name: ListSubscriptionsDueForSync :many
SELECT s.id, s.calendar_id, s.source_url, c.owner_id
FROM calendar_subscriptions s
JOIN calendars c ON c.id = s.calendar_id AND c.deleted_at IS NULL
WHERE s.sync_interval_minutes IS NOT NULL
  AND s.sync_interval_minutes > 0
  AND (s.last_synced_at IS NULL
       OR s.last_synced_at + make_interval(mins => s.sync_interval_minutes::numeric) <= now());
