-- name: GetDiscordPostLinkByPostID :one
SELECT post_id, discord_message_id, discord_thread_id, created_at
FROM discord_post_links
WHERE post_id = sqlc.arg(post_id);

-- name: GetDiscordPostLinkByMessageID :one
SELECT post_id, discord_message_id, discord_thread_id, created_at
FROM discord_post_links
WHERE discord_message_id = sqlc.arg(discord_message_id);

-- name: GetDiscordPostLinkByThreadID :one
SELECT post_id, discord_message_id, discord_thread_id, created_at
FROM discord_post_links
WHERE discord_thread_id = sqlc.arg(discord_thread_id)
  AND discord_thread_id <> '';

-- name: UpsertDiscordPostLink :exec
INSERT INTO discord_post_links (
  post_id, discord_message_id, discord_thread_id, created_at
)
VALUES (
  sqlc.arg(post_id),
  sqlc.arg(discord_message_id),
  sqlc.arg(discord_thread_id),
  sqlc.arg(created_at)
)
ON CONFLICT (post_id) DO UPDATE SET
  discord_message_id = EXCLUDED.discord_message_id,
  discord_thread_id = CASE
    WHEN EXCLUDED.discord_thread_id <> '' THEN EXCLUDED.discord_thread_id
    ELSE discord_post_links.discord_thread_id
  END;
