projects/sdk/src/api-errors.ts

import {
    operationDetails,
    operationHint,
    type FluxerlyErrorOptions,
    type OperationErrorOptions,
    type OperationOutcome,
} from "./errors.js"
import type { InputValidationDetail } from "./input-validation.js"
import type { PermissionName } from "./helpers.js"
import { record } from "#sdk/internal/decode/primitives"
import { permissionLabel as label } from "#sdk/internal/permission-labels"
import {
    permissionRequirement,
    requiredPermissionsHint,
    threadSend,
    type PermissionRequirement,
} from "#sdk/internal/permission-requirements"
/**
 * @internal Reviewed Fluxer codes behind ApiErrorDetail. Not part of the supported API
 *
 * @category Errors
 */
export const apiErrorMappings = {
    MISSING_ACCESS: { code: "missingAccess", explanation: "Fluxer denied access to the requested resource" },
    MISSING_PERMISSIONS: {
        code: "missingPermissions",
        explanation: "Fluxer reports that the bot lacks a required permission",
    },
    COMMUNICATION_DISABLED: {
        code: "communicationDisabled",
        explanation: "Fluxer reports that communication is disabled for this operation",
    },
    CANNOT_SEND_MESSAGES_TO_USER: {
        code: "cannotSendMessagesToUser",
        explanation: "Fluxer rejected delivery of this message to the requested user",
    },
    CANNOT_SEND_EMPTY_MESSAGE: {
        code: "cannotSendEmptyMessage",
        explanation: "Fluxer requires message content, an embed, an attachment, or a sticker",
    },
    CANNOT_MODIFY_SYSTEM_WEBHOOK: {
        code: "cannotModifySystemWebhook",
        explanation: "Fluxer does not allow editing a system message, pinning it or starting a thread from it",
    },
    ANNOUNCEMENT_CHANNEL_REQUIRED: {
        code: "announcementChannelRequired",
        explanation: "Fluxer requires an announcement channel for this operation",
    },
    CHANNEL_ALREADY_FOLLOWED: {
        code: "channelAlreadyFollowed",
        explanation: "The destination channel already receives updates from this announcement channel",
    },
    CHANNEL_HAS_FOLLOWED_CHANNELS: {
        code: "channelHasFollowedChannels",
        explanation: "The channel receives followed-channel updates and cannot become an announcement channel",
    },
    CHANNEL_TYPE_CONVERSION_NOT_SUPPORTED: {
        code: "channelTypeConversionNotSupported",
        explanation: "Fluxer rejected the requested channel type conversion",
    },
    FOLLOW_TARGET_CONTENT_WARNING_REQUIRED: {
        code: "followTargetContentWarningRequired",
        explanation:
            "The announcement source has a content warning but the destination has no warning or age restriction",
    },
    FOLLOW_TARGET_NOT_AGE_RESTRICTED: {
        code: "followTargetNotAgeRestricted",
        explanation: "The announcement source is age-restricted but the destination is not",
    },
    INVALID_FOLLOW_TARGET_CHANNEL: {
        code: "invalidFollowTargetChannel",
        explanation: "Fluxer requires a community text channel as the follow destination",
    },
    MESSAGE_ALREADY_CROSSPOSTED: {
        code: "messageAlreadyCrossposted",
        explanation: "The message has already been published",
    },
    MESSAGE_NOT_CROSSPOSTABLE: {
        code: "messageNotCrosspostable",
        explanation: "Fluxer cannot publish replies, system messages, forwarded messages or received crosspost copies",
    },
    MESSAGE_CROSSPOST_RATE_LIMITED: {
        code: "messageCrosspostRateLimited",
        explanation: "The announcement channel has reached its publishing rate limit",
    },
    PUBLISHED_MESSAGE_EDIT_RATE_LIMITED: {
        code: "publishedMessageEditRateLimited",
        explanation: "The published message has reached its editing rate limit",
    },
    INVALID_CHANNEL_TYPE: {
        code: "invalidChannelType",
        explanation: "Fluxer does not allow this operation for the type of this channel",
    },
    CHANNEL_HAS_THREADS: {
        code: "channelHasThreads",
        explanation: "The channel has private threads and cannot become an announcement channel",
    },
    THREAD_ALREADY_CREATED_FOR_MESSAGE: {
        code: "threadAlreadyCreated",
        explanation: "The message already has a thread",
    },
    THREAD_ARCHIVED: {
        code: "threadArchived",
        explanation: "Fluxer does not allow this operation in an archived thread",
    },
    THREAD_LOCKED: {
        code: "threadLocked",
        explanation: "Fluxer allows only members who can manage threads to act in a locked thread",
    },
    FORUM_TAG_NAMES_MUST_BE_UNIQUE: {
        code: "forumTagNamesNotUnique",
        explanation: "Fluxer requires every tag of a forum or media channel to have a different name",
    },
    FORUM_TAG_REQUIRED: {
        code: "forumTagRequired",
        explanation: "The forum or media channel requires every post to have at least one tag",
    },
    NO_TAGS_AVAILABLE_TO_NON_MODERATORS: {
        code: "noTagsAvailable",
        explanation: "The channel requires a tag on every post but has no tag that is not moderated",
    },
    HIDE_MEDIA_DOWNLOAD_OPTION_MEDIA_ONLY: {
        code: "mediaChannelRequired",
        explanation: "Fluxer accepts the flag that hides download options only on a media channel",
    },
    WEBHOOK_FORUM_TARGET_REQUIRED: {
        code: "webhookForumTargetRequired",
        explanation: "A webhook in a forum or media channel needs either a post name or an existing post to send to",
    },
    WEBHOOK_THREAD_NAME_REQUIRES_FORUM: {
        code: "webhookThreadNameRequiresForum",
        explanation: "Fluxer accepts a post name and tags only from a webhook in a forum or media channel",
    },
    CAPTCHA_REQUIRED: { code: "captchaRequired", explanation: "Fluxer requires CAPTCHA verification" },
    INVALID_CAPTCHA: { code: "invalidCaptcha", explanation: "Fluxer rejected the CAPTCHA verification" },
    INVALID_FORM_BODY: { code: "invalidFormBody", explanation: "Fluxer rejected one or more request fields" },
    VALIDATION_ERROR: { code: "invalidFormBody", explanation: "Fluxer rejected one or more request fields" },
    UNKNOWN_APPLICATION: { code: "unknownResource", explanation: "The requested application was not found" },
    UNKNOWN_BAN: { code: "unknownBan", explanation: "The requested user is not banned in this community" },
    UNKNOWN_CHANNEL: { code: "unknownResource", explanation: "The requested channel was not found" },
    UNKNOWN_CONNECTION_PROVIDER: {
        code: "unknownConnectionProvider",
        explanation: "The requested connection provider was not found",
    },
    UNKNOWN_EMOJI: { code: "unknownResource", explanation: "The requested emoji was not found" },
    UNKNOWN_FORUM_TAG: { code: "unknownResource", explanation: "The requested forum tag was not found" },
    UNKNOWN_GUILD: { code: "unknownResource", explanation: "The requested community was not found" },
    UNKNOWN_INVITE: { code: "unknownResource", explanation: "The requested invite was not found" },
    UNKNOWN_MEMBER: { code: "unknownResource", explanation: "The requested member was not found" },
    UNKNOWN_MESSAGE: { code: "unknownResource", explanation: "The requested message was not found" },
    UNKNOWN_ROLE: { code: "unknownResource", explanation: "The requested role was not found" },
    UNKNOWN_STICKER: { code: "unknownResource", explanation: "The requested sticker was not found" },
    UNKNOWN_THREAD_MEMBER: { code: "unknownResource", explanation: "The requested thread member was not found" },
    UNKNOWN_USER: { code: "unknownResource", explanation: "The requested user was not found" },
    UNKNOWN_WEBHOOK: { code: "unknownResource", explanation: "The requested webhook was not found" },
    MISSING_OAUTH_SCOPE: { code: "missingOAuthScope", explanation: "The OAuth token lacks a required scope" },
    CANNOT_EDIT_OTHER_USER_MESSAGE: {
        code: "cannotEditOtherUserMessage",
        explanation: "Fluxer does not allow editing another user's message",
    },
    CANNOT_SEND_MESSAGES_IN_NON_TEXT_CHANNEL: {
        code: "cannotSendMessagesInNonTextChannel",
        explanation: "Fluxer does not allow messages in the requested channel type",
    },
    CONTENT_BLOCKED: { code: "contentBlocked", explanation: "Fluxer blocked the submitted content" },
    DIRECT_MESSAGES_DISABLED: {
        code: "directMessagesDisabled",
        explanation: "Direct messages are turned off on this Fluxer instance",
    },
    COMMUNITY_MEMBER_DMS_DISABLED: {
        code: "communityMemberDmsDisabled",
        explanation: "This community has direct messages between members turned off",
    },
    EXPLICIT_CONTENT_CANNOT_BE_SENT: {
        code: "explicitContentCannotBeSent",
        explanation: "Fluxer blocked explicit content for this delivery",
    },
    FILE_SIZE_TOO_LARGE: { code: "fileSizeTooLarge", explanation: "A submitted file exceeds Fluxer's limit" },
    FEATURE_TEMPORARILY_DISABLED: {
        code: "featureTemporarilyDisabled",
        explanation:
            "Fluxer has turned this operation off, either for this community or for the whole instance, such as sending messages, reactions, invites or search",
    },
    SLOWMODE_RATE_LIMITED: { code: "slowmodeRateLimited", explanation: "Fluxer's channel slowmode is active" },
    GUILD_VERIFICATION_REQUIRED: {
        code: "guildVerificationRequired",
        explanation: "Fluxer requires community verification for this operation",
    },
    GUILD_EMAIL_VERIFICATION_REQUIRED: {
        code: "guildVerificationRequired",
        explanation: "Fluxer requires community email verification for this operation",
    },
    TWO_FACTOR_REQUIRED: {
        code: "twoFactorRequired",
        explanation: "Fluxer requires two-factor authentication on the calling account for this operation",
    },
    BOT_ALREADY_IN_GUILD: { code: "botAlreadyInGuild", explanation: "The bot is already in the requested community" },
    BOT_IS_PRIVATE: { code: "botIsPrivate", explanation: "Fluxer does not allow adding this private bot" },
    NOT_A_BOT_APPLICATION: { code: "notBotApplication", explanation: "The requested application is not a bot" },
    APPLICATION_NOT_OWNED: {
        code: "applicationNotOwned",
        explanation: "The caller does not own the requested application",
    },
    RESOURCE_LOCKED: {
        code: "resourceLocked",
        explanation: "Fluxer has temporarily locked the requested resource",
    },
    ACCESS_DENIED: { code: "accessDenied", explanation: "Fluxer denied this request" },
    BAD_REQUEST: {
        code: "badRequest",
        explanation: "The request was malformed or failed a Fluxer precondition",
    },
    CONFLICT: { code: "conflict", explanation: "The request conflicts with Fluxer's current resource state" },
    FORBIDDEN: { code: "forbidden", explanation: "Fluxer forbids this request" },
    NOT_FOUND: { code: "notFound", explanation: "Fluxer could not find the requested resource" },
    RATE_LIMITED: { code: "rateLimited", explanation: "Fluxer rate-limited this request" },
    SERVICE_UNAVAILABLE: { code: "serviceUnavailable", explanation: "Fluxer service is temporarily unavailable" },
    UNAUTHORIZED: { code: "unauthorized", explanation: "Fluxer rejected the request credentials" },
    INVALID_TOKEN: { code: "unauthorized", explanation: "Fluxer rejected the request token" },
    MISSING_AUTHORIZATION: { code: "unauthorized", explanation: "Fluxer requires request credentials" },
    GONE: { code: "gone", explanation: "Fluxer reports that this resource is no longer available" },
    BAD_GATEWAY: { code: "serviceFailure", explanation: "Fluxer's gateway returned an invalid upstream response" },
    GATEWAY_TIMEOUT: { code: "serviceFailure", explanation: "Fluxer's gateway timed out" },
    INTERNAL_SERVER_ERROR: { code: "serviceFailure", explanation: "Fluxer encountered an internal error" },
    NOT_IMPLEMENTED: { code: "notImplemented", explanation: "Fluxer does not implement this operation" },
    CANNOT_EXECUTE_ON_DM: {
        code: "cannotExecuteOnDirectMessage",
        explanation: "Fluxer does not allow this operation in a direct message",
    },
    INVITES_DISABLED: { code: "invitesDisabled", explanation: "Fluxer has disabled invites for this community" },
    FEATURE_NOT_AVAILABLE_SELF_HOSTED: {
        code: "featureNotAvailableSelfHosted",
        explanation: "Fluxer does not offer this feature on this self-hosted instance",
    },
    USER_NOT_IN_VOICE: {
        code: "userNotInVoice",
        explanation: "Fluxer reports that the member is not connected to voice",
    },
    NSFW_CONTENT_AGE_RESTRICTED: {
        code: "nsfwContentAgeRestricted",
        explanation:
            "Fluxer refused age-restricted content in a channel that is not age-restricted, such as a forwarded message with age-restricted media",
    },
    SINGLE_COMMUNITY_CANNOT_LEAVE: {
        code: "singleCommunityCannotLeave",
        explanation: "This Fluxer instance runs as a single community, which members cannot leave",
    },
    DISCOVERY_DISABLED: {
        code: "discoveryDisabled",
        explanation: "Community directory discovery is turned off on this Fluxer instance",
    },
    DISCOVERY_INSUFFICIENT_MEMBERS: {
        code: "discoveryInsufficientMembers",
        explanation: "The community has fewer members than this instance requires for a discovery listing",
    },
    DISCOVERY_ALREADY_APPLIED: {
        code: "discoveryAlreadyApplied",
        explanation: "The community already has a pending or approved discovery application",
    },
    DISCOVERY_APPLICATION_NOT_FOUND: {
        code: "discoveryApplicationNotFound",
        explanation: "The community has no discovery application",
    },
    DISCOVERY_APPLICATION_ALREADY_REVIEWED: {
        code: "discoveryApplicationAlreadyReviewed",
        explanation: "Fluxer already rejected or removed this discovery application, so it can no longer be edited",
    },
    MAX_ACTIVE_THREADS: { code: "resourceLimit", explanation: "Fluxer's community active-thread limit was reached" },
    MAX_CATEGORY_CHANNELS: { code: "resourceLimit", explanation: "Fluxer's category-channel limit was reached" },
    MAX_EMOJIS: { code: "resourceLimit", explanation: "Fluxer's emoji limit was reached" },
    MAX_FORUM_TAGS: { code: "resourceLimit", explanation: "Fluxer's forum-tag limit was reached" },
    MAX_GUILD_CHANNELS: { code: "resourceLimit", explanation: "Fluxer's community channel limit was reached" },
    MAX_GUILD_MEMBERS: { code: "resourceLimit", explanation: "Fluxer's community member limit was reached" },
    MAX_GUILD_ROLES: { code: "resourceLimit", explanation: "Fluxer's community role limit was reached" },
    MAX_INVITES: { code: "resourceLimit", explanation: "Fluxer's community invite limit was reached" },
    MAX_PINNED_THREADS_IN_FORUM: {
        code: "resourceLimit",
        explanation: "Fluxer's pinned-post limit for a forum or media channel was reached",
    },
    MAX_REACTIONS: { code: "resourceLimit", explanation: "Fluxer's reaction limit was reached" },
    MAX_STICKERS: { code: "resourceLimit", explanation: "Fluxer's sticker limit was reached" },
    MAX_THREAD_MEMBERS: { code: "resourceLimit", explanation: "Fluxer's thread member limit was reached" },
    MAX_WEBHOOKS_PER_CHANNEL: {
        code: "resourceLimit",
        explanation: "Fluxer's channel-webhook limit was reached",
    },
    MAX_WEBHOOKS_PER_GUILD: { code: "resourceLimit", explanation: "Fluxer's community webhook limit was reached" },
} as const satisfies Readonly<Record<ApiProviderCode, { readonly code: ApiErrorCode; readonly explanation: string }>>

/**
 * @internal Reviewed validation codes behind ApiValidationErrorDetail. Not part of the supported API
 *
 * @category Errors
 */
export const validationErrorMappings = {
    ATTACHMENTS_NOT_ALLOWED_FOR_MESSAGE: "Attachments are not allowed for this message",
    CANNOT_DELETE_MORE_THAN_100_MESSAGES: "Fluxer allows at most 100 messages in one deletion request",
    CANNOT_SEND_EMPTY_MESSAGE: "Fluxer requires message content, an embed, an attachment, or a sticker",
    CANNOT_SPECIFY_BOTH_BEFORE_AND_AFTER: "Fluxer does not allow both before and after pagination bounds",
    CONTENT_EXCEEDS_MAX_LENGTH: "Submitted text exceeds Fluxer's limit",
    DUPLICATE_ATTACHMENT_IDS_NOT_ALLOWED: "Attachment identifiers must be unique",
    DUPLICATE_FILE_INDEX: "Attachment file indexes must be unique",
    EMBEDS_EXCEED_MAX_CHARACTERS: "Submitted embeds exceed Fluxer's combined text limit",
    FILE_INDEX_EXCEEDS_MAXIMUM: "An attachment file index exceeds Fluxer's limit",
    INVALID_AUDIT_LOG_REASON: "The audit-log reason is invalid",
    INVALID_FORMAT: "A submitted value has an invalid format",
    INVALID_MESSAGE_DATA: "The submitted message data is invalid",
    INVALID_SNOWFLAKE: "A submitted identifier is invalid",
    INVALID_SNOWFLAKE_FORMAT: "A submitted identifier has an invalid format",
    INVALID_URL_FORMAT:
        "A submitted URL is not accepted, such as one that is not http or https, contains a user name or password, or has no top-level domain",
    MESSAGE_IDS_CANNOT_BE_EMPTY: "At least one message identifier is required",
    STRING_LENGTH_INVALID: "A submitted string has an invalid length",
    TOO_MANY_EMBEDS: "Too many embeds were submitted",
    TOO_MANY_FILES: "Too many files were submitted",
    TOO_LARGE: "Submitted data exceeds Fluxer's limit",
    ATTACHMENT_FIELDS_REQUIRED: "Required attachment fields are missing",
    INVALID_TIMEOUT_VALUE: "The requested timeout is invalid",
    TIMEOUT_CANNOT_EXCEED_365_DAYS: "The requested timeout exceeds Fluxer's limit",
    RECIPIENT_IDS_CANNOT_BE_EMPTY: "At least one recipient identifier is required",
    DUPLICATE_RECIPIENTS_NOT_ALLOWED: "Recipient identifiers must be unique",
    VANITY_URL_CODE_ALREADY_TAKEN: "The vanity URL code is already taken",
    VANITY_URL_CODE_LENGTH_INVALID: "The vanity URL code has an invalid length",
    VANITY_URL_INVALID_CHARACTERS: "The vanity URL code has invalid characters",
    VOICE_MESSAGES_ATTACHMENT_MUST_BE_AUDIO: "A voice note or an attachment with a waveform must be an audio file",
    VOICE_MESSAGES_ATTACHMENT_WAVEFORM_REQUIRED: "A voice note's attachment needs a waveform",
    VOICE_MESSAGES_ATTACHMENT_DURATION_REQUIRED: "A voice note's attachment needs a duration",
    VOICE_MESSAGES_CANNOT_HAVE_CONTENT: "A voice note cannot have message content",
    VOICE_MESSAGES_CANNOT_HAVE_EMBEDS: "A voice note cannot have embeds",
    VOICE_MESSAGES_CANNOT_HAVE_FAVORITE_MEMES: "A voice note cannot have a saved meme",
    VOICE_MESSAGES_CANNOT_HAVE_STICKERS: "A voice note cannot have stickers",
    VOICE_MESSAGES_DURATION_EXCEEDS_LIMIT: "The voice note is longer than this instance allows",
    VOICE_MESSAGES_REQUIRE_SINGLE_ATTACHMENT: "A voice note needs exactly one attachment",
} as const satisfies Readonly<Record<ApiValidationCode, string>>

/**
 * Stable SDK category of a recognized Fluxer API rejection, read from ApiErrorDetail.code.
 * Branch on this rather than on providerCode when several server codes mean the same thing, such as every resource limit.
 * Announcement, follow, channel conversion and publishing preconditions have distinct categories. Publishing and
 * published-message editing limits are separate from the general rateLimited category. Thread state, forum tag and
 * webhook post preconditions also have distinct categories, while the thread, tag and pinned-post limits join
 * resourceLimit and a missing forum tag or thread member joins unknownResource.
 * The name cannotModifySystemWebhook comes from Fluxer's code. Fluxer sends it for system messages, not webhooks
 *
 * @category Errors
 */
export type ApiErrorCode =
    | "missingAccess"
    | "missingPermissions"
    | "communicationDisabled"
    | "cannotSendMessagesToUser"
    | "cannotSendEmptyMessage"
    | "cannotModifySystemWebhook"
    | "announcementChannelRequired"
    | "channelAlreadyFollowed"
    | "channelHasFollowedChannels"
    | "channelTypeConversionNotSupported"
    | "followTargetContentWarningRequired"
    | "followTargetNotAgeRestricted"
    | "invalidFollowTargetChannel"
    | "messageAlreadyCrossposted"
    | "messageNotCrosspostable"
    | "messageCrosspostRateLimited"
    | "publishedMessageEditRateLimited"
    | "invalidChannelType"
    | "channelHasThreads"
    | "threadAlreadyCreated"
    | "threadArchived"
    | "threadLocked"
    | "forumTagNamesNotUnique"
    | "forumTagRequired"
    | "noTagsAvailable"
    | "mediaChannelRequired"
    | "webhookForumTargetRequired"
    | "webhookThreadNameRequiresForum"
    | "captchaRequired"
    | "invalidCaptcha"
    | "invalidFormBody"
    | "unknownBan"
    | "unknownConnectionProvider"
    | "unknownResource"
    | "missingOAuthScope"
    | "cannotEditOtherUserMessage"
    | "cannotSendMessagesInNonTextChannel"
    | "contentBlocked"
    | "communityMemberDmsDisabled"
    | "directMessagesDisabled"
    | "explicitContentCannotBeSent"
    | "fileSizeTooLarge"
    | "featureTemporarilyDisabled"
    | "slowmodeRateLimited"
    | "guildVerificationRequired"
    | "twoFactorRequired"
    | "botAlreadyInGuild"
    | "botIsPrivate"
    | "notBotApplication"
    | "applicationNotOwned"
    | "resourceLocked"
    | "accessDenied"
    | "badRequest"
    | "conflict"
    | "forbidden"
    | "notFound"
    | "rateLimited"
    | "serviceUnavailable"
    | "unauthorized"
    | "gone"
    | "serviceFailure"
    | "notImplemented"
    | "cannotExecuteOnDirectMessage"
    | "invitesDisabled"
    | "featureNotAvailableSelfHosted"
    | "userNotInVoice"
    | "nsfwContentAgeRestricted"
    | "singleCommunityCannotLeave"
    | "discoveryDisabled"
    | "discoveryInsufficientMembers"
    | "discoveryAlreadyApplied"
    | "discoveryApplicationNotFound"
    | "discoveryApplicationAlreadyReviewed"
    | "resourceLimit"

/**
 * Exact Fluxer server code that the SDK recognizes, read from ApiErrorDetail.providerCode.
 * An unrecognized server code produces no ApiErrorDetail
 *
 * @category Errors
 */
export type ApiProviderCode =
    | "MISSING_ACCESS"
    | "MISSING_PERMISSIONS"
    | "COMMUNICATION_DISABLED"
    | "CANNOT_SEND_MESSAGES_TO_USER"
    | "CANNOT_SEND_EMPTY_MESSAGE"
    | "CANNOT_MODIFY_SYSTEM_WEBHOOK"
    | "ANNOUNCEMENT_CHANNEL_REQUIRED"
    | "CHANNEL_ALREADY_FOLLOWED"
    | "CHANNEL_HAS_FOLLOWED_CHANNELS"
    | "CHANNEL_TYPE_CONVERSION_NOT_SUPPORTED"
    | "FOLLOW_TARGET_CONTENT_WARNING_REQUIRED"
    | "FOLLOW_TARGET_NOT_AGE_RESTRICTED"
    | "INVALID_FOLLOW_TARGET_CHANNEL"
    | "MESSAGE_ALREADY_CROSSPOSTED"
    | "MESSAGE_NOT_CROSSPOSTABLE"
    | "MESSAGE_CROSSPOST_RATE_LIMITED"
    | "PUBLISHED_MESSAGE_EDIT_RATE_LIMITED"
    | "INVALID_CHANNEL_TYPE"
    | "CHANNEL_HAS_THREADS"
    | "THREAD_ALREADY_CREATED_FOR_MESSAGE"
    | "THREAD_ARCHIVED"
    | "THREAD_LOCKED"
    | "FORUM_TAG_NAMES_MUST_BE_UNIQUE"
    | "FORUM_TAG_REQUIRED"
    | "NO_TAGS_AVAILABLE_TO_NON_MODERATORS"
    | "HIDE_MEDIA_DOWNLOAD_OPTION_MEDIA_ONLY"
    | "WEBHOOK_FORUM_TARGET_REQUIRED"
    | "WEBHOOK_THREAD_NAME_REQUIRES_FORUM"
    | "CAPTCHA_REQUIRED"
    | "INVALID_CAPTCHA"
    | "INVALID_FORM_BODY"
    | "VALIDATION_ERROR"
    | "UNKNOWN_APPLICATION"
    | "UNKNOWN_BAN"
    | "UNKNOWN_CHANNEL"
    | "UNKNOWN_CONNECTION_PROVIDER"
    | "UNKNOWN_EMOJI"
    | "UNKNOWN_FORUM_TAG"
    | "UNKNOWN_GUILD"
    | "UNKNOWN_INVITE"
    | "UNKNOWN_MEMBER"
    | "UNKNOWN_MESSAGE"
    | "UNKNOWN_ROLE"
    | "UNKNOWN_STICKER"
    | "UNKNOWN_THREAD_MEMBER"
    | "UNKNOWN_USER"
    | "UNKNOWN_WEBHOOK"
    | "MISSING_OAUTH_SCOPE"
    | "CANNOT_EDIT_OTHER_USER_MESSAGE"
    | "CANNOT_SEND_MESSAGES_IN_NON_TEXT_CHANNEL"
    | "CONTENT_BLOCKED"
    | "COMMUNITY_MEMBER_DMS_DISABLED"
    | "DIRECT_MESSAGES_DISABLED"
    | "EXPLICIT_CONTENT_CANNOT_BE_SENT"
    | "FILE_SIZE_TOO_LARGE"
    | "FEATURE_TEMPORARILY_DISABLED"
    | "SLOWMODE_RATE_LIMITED"
    | "GUILD_VERIFICATION_REQUIRED"
    | "GUILD_EMAIL_VERIFICATION_REQUIRED"
    | "TWO_FACTOR_REQUIRED"
    | "BOT_ALREADY_IN_GUILD"
    | "BOT_IS_PRIVATE"
    | "NOT_A_BOT_APPLICATION"
    | "APPLICATION_NOT_OWNED"
    | "RESOURCE_LOCKED"
    | "ACCESS_DENIED"
    | "BAD_REQUEST"
    | "CONFLICT"
    | "FORBIDDEN"
    | "NOT_FOUND"
    | "RATE_LIMITED"
    | "SERVICE_UNAVAILABLE"
    | "UNAUTHORIZED"
    | "INVALID_TOKEN"
    | "MISSING_AUTHORIZATION"
    | "GONE"
    | "BAD_GATEWAY"
    | "GATEWAY_TIMEOUT"
    | "INTERNAL_SERVER_ERROR"
    | "NOT_IMPLEMENTED"
    | "CANNOT_EXECUTE_ON_DM"
    | "INVITES_DISABLED"
    | "FEATURE_NOT_AVAILABLE_SELF_HOSTED"
    | "USER_NOT_IN_VOICE"
    | "NSFW_CONTENT_AGE_RESTRICTED"
    | "SINGLE_COMMUNITY_CANNOT_LEAVE"
    | "DISCOVERY_DISABLED"
    | "DISCOVERY_INSUFFICIENT_MEMBERS"
    | "DISCOVERY_ALREADY_APPLIED"
    | "DISCOVERY_APPLICATION_NOT_FOUND"
    | "DISCOVERY_APPLICATION_ALREADY_REVIEWED"
    | "MAX_ACTIVE_THREADS"
    | "MAX_CATEGORY_CHANNELS"
    | "MAX_EMOJIS"
    | "MAX_FORUM_TAGS"
    | "MAX_GUILD_CHANNELS"
    | "MAX_GUILD_MEMBERS"
    | "MAX_GUILD_ROLES"
    | "MAX_INVITES"
    | "MAX_PINNED_THREADS_IN_FORUM"
    | "MAX_REACTIONS"
    | "MAX_STICKERS"
    | "MAX_THREAD_MEMBERS"
    | "MAX_WEBHOOKS_PER_CHANNEL"
    | "MAX_WEBHOOKS_PER_GUILD"

/**
 * Exact Fluxer validation code that the SDK recognizes, read from ApiValidationErrorDetail.providerCode.
 * An unrecognized validation code stays in validationErrors with a generic explanation when it has a safe code shape
 *
 * @category Errors
 */
export type ApiValidationCode =
    | "ATTACHMENTS_NOT_ALLOWED_FOR_MESSAGE"
    | "CANNOT_DELETE_MORE_THAN_100_MESSAGES"
    | "CANNOT_SEND_EMPTY_MESSAGE"
    | "CANNOT_SPECIFY_BOTH_BEFORE_AND_AFTER"
    | "CONTENT_EXCEEDS_MAX_LENGTH"
    | "DUPLICATE_ATTACHMENT_IDS_NOT_ALLOWED"
    | "DUPLICATE_FILE_INDEX"
    | "EMBEDS_EXCEED_MAX_CHARACTERS"
    | "FILE_INDEX_EXCEEDS_MAXIMUM"
    | "INVALID_AUDIT_LOG_REASON"
    | "INVALID_FORMAT"
    | "INVALID_MESSAGE_DATA"
    | "INVALID_SNOWFLAKE"
    | "INVALID_SNOWFLAKE_FORMAT"
    | "INVALID_URL_FORMAT"
    | "MESSAGE_IDS_CANNOT_BE_EMPTY"
    | "STRING_LENGTH_INVALID"
    | "TOO_MANY_EMBEDS"
    | "TOO_MANY_FILES"
    | "TOO_LARGE"
    | "ATTACHMENT_FIELDS_REQUIRED"
    | "INVALID_TIMEOUT_VALUE"
    | "TIMEOUT_CANNOT_EXCEED_365_DAYS"
    | "RECIPIENT_IDS_CANNOT_BE_EMPTY"
    | "DUPLICATE_RECIPIENTS_NOT_ALLOWED"
    | "VANITY_URL_CODE_ALREADY_TAKEN"
    | "VANITY_URL_CODE_LENGTH_INVALID"
    | "VANITY_URL_INVALID_CHARACTERS"
    | "VOICE_MESSAGES_ATTACHMENT_MUST_BE_AUDIO"
    | "VOICE_MESSAGES_ATTACHMENT_WAVEFORM_REQUIRED"
    | "VOICE_MESSAGES_ATTACHMENT_DURATION_REQUIRED"
    | "VOICE_MESSAGES_CANNOT_HAVE_CONTENT"
    | "VOICE_MESSAGES_CANNOT_HAVE_EMBEDS"
    | "VOICE_MESSAGES_CANNOT_HAVE_FAVORITE_MEMES"
    | "VOICE_MESSAGES_CANNOT_HAVE_STICKERS"
    | "VOICE_MESSAGES_DURATION_EXCEEDS_LIMIT"
    | "VOICE_MESSAGES_REQUIRE_SINGLE_ATTACHMENT"

/** A validation error reported by Fluxer, with a fixed SDK explanation.
 * This is a server rejection, not a problem found by local input checks.
 * It includes the rejected field path when Fluxer supplied one, but never the rejected value or localized server message
 *
 * @category Errors
 */
export interface ApiValidationErrorDetail {
    /**
     * Fluxer validation code. A code this SDK version does not recognize is kept when it is an uppercase code of at most
     * 64 characters, with a generic explanation, so its field path is not lost. An empty string when Fluxer named the
     * field without a code
     */
    readonly providerCode: ApiValidationCode | (string & {})
    /** Fixed SDK explanation of the validation code */
    readonly explanation: string
    /** Request field path that Fluxer rejected, such as embeds.0.title, when supplied in a plain dotted form */
    readonly path?: string
}

/**
 * Safe details about a Fluxer API rejection, available in an operation error's apiError field.
 * The code is the SDK's category. The providerCode is the exact server code that the SDK recognizes.
 * The explanation is fixed SDK text, not the server's message or text to show directly to users.
 * If the SDK does not recognize the server code, apiError is null rather than containing unreviewed text, and the
 * error's details.providerCode names the unrecognized code when it is an uppercase code of at most 64 characters.
 * For form errors, validationErrors contains at most 32 validation codes with their field paths, without messages or rejected values.
 * These details never contain the response body, localized message, rejected value or private caller data.
 * Responses from presigned upload destinations do not receive this classification
 *
 * For code missingPermissions, the operation error's details.requiredPermissions lists the permissions that Fluxer
 * checks for the failed operation, as keys of Permissions such as ViewChannel, and the error's hint names them.
 * Fluxer does not report which one is missing, so the bot may already have some of them. The list covers the
 * operation's usual path, and the hint adds other checks behind the same rejection, such as role hierarchy or a
 * permission that only some inputs need. Other rejections, rest.request and operations whose checks depend on data the
 * SDK does not have, such as who created an emoji, carry no details.requiredPermissions and keep a general hint
 *
 * @example
 * ```ts
 * import type { ApiErrorDetail } from "@neontechspace/fluxerly"
 *
 * export function formatApiErrorDetail(detail: ApiErrorDetail): string {
 *     // Branch on the category, which groups related server codes such as every resource limit
 *     if (detail.code === "resourceLimit") return `Limit reached: ${detail.explanation}`
 *     const fields = detail.validationErrors?.map((error) => error.path ?? error.providerCode) ?? []
 *     return `${detail.providerCode}: ${detail.explanation}${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`
 * }
 * ```
 *
 * @category Errors
 */
export interface ApiErrorDetail {
    /** Stable SDK category for this recognized rejection. Several Fluxer codes can share one category */
    readonly code: ApiErrorCode
    /** Exact recognized Fluxer server code */
    readonly providerCode: ApiProviderCode
    /** Fixed SDK explanation, never Fluxer's localized response text */
    readonly explanation: string
    /**
     * Present only when code is invalidFormBody. Holds at most 32 validation codes with field paths, without Fluxer
     * messages or rejected values
     */
    readonly validationErrors?: readonly ApiValidationErrorDetail[]
}

/** Shape of a Fluxer error code that is safe to keep even when this SDK version does not describe it */
const providerCodePattern = /^[A-Z][A-Z0-9_]{0,63}$/

/** The explanation of a validation entry that names a field without a code */
const uncodedExplanation = "Fluxer rejected this field without a code"

function validationDetails(value: unknown): readonly ApiValidationErrorDetail[] {
    if (!Array.isArray(value)) return Object.freeze([])
    const details: ApiValidationErrorDetail[] = []
    for (const item of value) {
        if (details.length === 32 || !record(item)) continue
        const path =
            typeof item.path === "string" &&
            /^[A-Za-z_][A-Za-z0-9_]*(?:\.(?:[A-Za-z_][A-Za-z0-9_]*|\d{1,4})){0,8}$/.test(item.path)
                ? item.path
                : undefined
        // Fluxer's schema makes the code optional, and some checks name only the field, such as a badge cursor
        // (packages/schema/src/domains/common/ErrorSchemas.ts:6-10 at 5f3fc0b1)
        if (item.code === undefined && path !== undefined) {
            details.push(Object.freeze({ providerCode: "", explanation: uncodedExplanation, path }))
            continue
        }
        if (typeof item.code !== "string") continue
        const known = Object.hasOwn(validationErrorMappings, item.code)
        if (!known && !providerCodePattern.test(item.code)) continue
        const explanation = known
            ? validationErrorMappings[item.code as keyof typeof validationErrorMappings]
            : "Fluxer rejected this field with a code that this SDK version does not describe"
        details.push(
            Object.freeze({
                providerCode: item.code,
                explanation,
                ...(path === undefined ? {} : { path }),
            }),
        )
    }
    return Object.freeze(details)
}

/** Return frozen, SDK-written details only for recognized Fluxer response codes. Return null for unknown codes */
export function apiErrorDetail(body: unknown): ApiErrorDetail | null {
    if (!record(body) || typeof body.code !== "string") return null
    if (!Object.hasOwn(apiErrorMappings, body.code)) return null
    const mapped = apiErrorMappings[body.code as keyof typeof apiErrorMappings]
    const detail = {
        code: mapped.code,
        providerCode: body.code,
        explanation: mapped.explanation,
        ...(body.code === "INVALID_FORM_BODY" || body.code === "VALIDATION_ERROR"
            ? { validationErrors: validationDetails(body.errors) }
            : {}),
    }
    return Object.freeze(detail) as ApiErrorDetail
}

/** @internal A Fluxer error code that apiErrorDetail does not recognize but that is safe to show, or null */
export function unrecognizedProviderCode(body: unknown): string | null {
    if (!record(body) || typeof body.code !== "string" || Object.hasOwn(apiErrorMappings, body.code)) return null
    return providerCodePattern.test(body.code) ? body.code : null
}

/**
 * @internal Suggested fixes by API error category. The rejection's explanation says what Fluxer refused, and this text
 * says what to change
 */
const apiErrorHints: Readonly<Record<ApiErrorCode, string>> = {
    missingPermissions:
        "Grant the bot's role the permission this operation needs in the community settings or the channel's permission overrides",
    missingAccess: `Give the bot's role ${label("ViewChannel")} for this channel or its category, and check that the bot is still in the community. For a private thread, ask a thread member to add the bot, or grant ${label("ManageThreads")} in the parent channel. Hidden community channels can also return UNKNOWN_CHANNEL (HTTP 404) instead`,
    unknownBan:
        "The user has no active ban in this community. Check the user ID, or list active bans with members.fetchBans",
    unknownConnectionProvider:
        "Check the connection provider ID. The provider may be removed or turned off on this instance",
    unknownResource:
        "Check the ID. The resource may be deleted or hidden from this bot, because Fluxer returns UNKNOWN_CHANNEL (HTTP 404) for a channel the bot cannot view",
    notFound:
        "Check the ID. The resource may be deleted or hidden from this bot, because Fluxer returns UNKNOWN_CHANNEL (HTTP 404) for a channel the bot cannot view",
    unauthorized:
        "Check the configured credential. A valid bot token can also be rejected when the application owner's account is closed, disabled or limited (ACCOUNT_LIMITED). For OAuth, check whether the authorizing user's account is closed or temporarily banned. A new token does not fix an account-standing rejection. The rejection alone does not identify the cause",
    invalidFormBody:
        "Correct the fields named in the message. The error's apiError.validationErrors lists them as data",
    cannotSendMessagesToUser: "The user does not accept direct messages from this bot, so retrying does not help",
    communityMemberDmsDisabled:
        "This community has MEMBER_DMS_DISABLED enabled, so retrying does not help unless a community administrator turns it off or the recipient already accepts direct messages",
    directMessagesDisabled:
        "This Fluxer instance has turned off direct messages, so retrying does not help. Ask its administrator if bots should be able to send them",
    communicationDisabled:
        "The bot is timed out in this community. Wait for the timeout to end, or ask a moderator to remove it",
    contentBlocked:
        "This instance's content filter blocked text, a link or a file in the request. Change or remove the blocked content and send again",
    cannotModifySystemWebhook: "Use an ordinary message or reply instead of a system message",
    cannotSendEmptyMessage: "Include content, an embed, an attachment or a sticker",
    announcementChannelRequired: "Use an announcement channel as the source of this operation",
    channelAlreadyFollowed: "Keep the existing follow or choose a destination that does not already follow this source",
    channelHasFollowedChannels: "Remove the channel-follower webhooks from this channel before converting it",
    channelTypeConversionNotSupported:
        "Convert only between community text and announcement channels, using the channel's current type as the source",
    followTargetContentWarningRequired:
        "Use a destination with a content warning or an age restriction, including inherited category or community settings",
    followTargetNotAgeRestricted:
        "Use an age-restricted destination, including inherited category or community settings",
    invalidFollowTargetChannel: "Use a community text channel as the follow destination",
    messageAlreadyCrossposted: "Edit the source message to update its published copies instead of publishing it again",
    messageNotCrosspostable:
        "Publish an ordinary source message rather than a reply, forwarded message or received crosspost copy",
    messageCrosspostRateLimited: "Wait before publishing another message in this channel",
    publishedMessageEditRateLimited: "Wait before editing this published message again",
    invalidChannelType: "Check the channel's type, because this operation does not accept it",
    channelHasThreads: "Delete the channel's private threads before converting it to an announcement channel",
    threadAlreadyCreated: "Use the existing thread, which has the same ID as the message",
    threadArchived: "Unarchive the thread first, by editing it with archived set to false, then repeat the operation",
    threadLocked: `Grant the bot's role ${label("ManageThreads")}, or ask a member who has it to unlock the thread`,
    forumTagNamesNotUnique: "Give every tag of the channel a different name",
    forumTagRequired: "Include at least one of the channel's tag IDs, because the channel requires a tag on every post",
    noTagsAvailable: "Add a tag that is not moderated to the channel, or turn off ChannelFlags.RequireTag",
    mediaChannelRequired: "Remove ChannelFlags.HideMediaDownloadOptions, because only a media channel accepts it",
    webhookForumTargetRequired: "Set threadName to start a post, or threadId to send into an existing post",
    webhookThreadNameRequiresForum:
        "Remove threadName and appliedTagIds, because only a webhook in a forum or media channel starts posts",
    cannotSendMessagesInNonTextChannel: "Send the message to a text channel",
    cannotEditOtherUserMessage: "Only messages that the bot sent can be edited",
    twoFactorRequired: "The application owner's account needs two-factor authentication enabled for this operation",
    slowmodeRateLimited: "Wait for the channel's slowmode interval before sending again",
    resourceLimit: "Remove unused items before creating more. Fluxer sets this limit",
    missingOAuthScope: "Request the missing scope when the user authorizes the application",
    fileSizeTooLarge:
        "Send a smaller file, compress it or split it into separate uploads. Fluxer rejected the file before applying the request",
    serviceUnavailable: "Fluxer had a temporary problem. Retry later",
    serviceFailure: "Fluxer had a temporary problem. Retry later",
    featureTemporarilyDisabled:
        "Instance staff turned this off, so retrying does not help until they turn it on again. Ask the instance's administrator if the bot needs it",
    explicitContentCannotBeSent:
        "Fluxer's media check found explicit content in an attachment, and this community's explicit content filter blocks it, or the recipient of a direct message blocks sensitive media. Send different media. In a community, an admin can give the bot a role or change the filter. A discoverable community always blocks it",
    userNotInVoice:
        "Check that the member is connected to voice before moving or disconnecting them. Fluxer also refuses a move into an occupied channel whose participants all use peer-to-peer voice, and retrying does not help while it stays that way",
    nsfwContentAgeRestricted:
        "Forward age-restricted content only into an age-restricted channel or community, or forward a different message",
    singleCommunityCannotLeave:
        "Retrying does not help. On a single-community instance, ask its administrator to remove the bot instead",
    discoveryDisabled:
        "This instance has discovery turned off, so retrying does not help. ResolvedInstance.discoveryEnabled reports this before any request",
    discoveryInsufficientMembers:
        "Apply again once the community has more members. discovery.fetchStatus reports whether it is eligible",
    discoveryAlreadyApplied:
        "Read the application with discovery.fetchStatus, and change a pending one with discovery.edit instead of applying again",
    discoveryApplicationNotFound: "Apply with discovery.apply first",
    discoveryApplicationAlreadyReviewed:
        "Read the result with discovery.fetchStatus, then apply again with discovery.apply if the community should be listed",
    resourceLocked: "Fluxer is applying another change to this resource. Wait briefly, then send the change again",
    cannotExecuteOnDirectMessage: "Use this operation in a community channel",
    invitesDisabled:
        "Invites are turned off for this community, so retrying does not help unless a community administrator enables them",
    featureNotAvailableSelfHosted:
        "This self-hosted Fluxer instance does not support this feature, so retrying does not help",
    guildVerificationRequired:
        "The community's verification level blocks this request. Check the calling account's verification status before trying again",
    botIsPrivate:
        "Only the application owner can add a private bot, or enable public installation in the application's Fluxer settings",
    applicationNotOwned: "Use credentials for the account that owns this application",
    captchaRequired:
        "Fluxer requires interactive CAPTCHA verification, which a bot cannot complete automatically, so retrying does not help",
    invalidCaptcha:
        "Fluxer rejected the CAPTCHA verification. Request a new challenge rather than repeating the same submission",
    botAlreadyInGuild: "The bot is already a member of this community, so no action is needed",
    notBotApplication: "Use a bot application ID rather than a non-bot application",
    badRequest: "Check the request parameters and resource state against Fluxer's requirements. Nothing was applied",
    conflict: "Fetch the resource's current state and reconcile it before repeating the change",
    gone: "This resource is permanently gone, so retrying does not help",
    notImplemented: "This Fluxer server does not implement this operation, so retrying does not help",
    accessDenied: "Check the bot's permissions, role position and access to this resource",
    forbidden: "Check the bot's permissions, role position and account eligibility for this resource",
    rateLimited: "The request was rate-limited. Wait before retrying",
}

/** Suggested fixes for the standard OAuth error codes that the SDK keeps in oauthError */
const oauthErrorHints: Readonly<Record<string, string>> = {
    invalid_grant:
        "Check the authorization code or refresh token for expiry, prior use and the correct redirect URI. For a code exchange, pass the original codeVerifier that produced the authorization request's codeChallenge. Also check whether the authorizing user's account is closed or temporarily banned. A new token or repeated authorization does not fix an account-standing rejection. The rejection alone does not identify the cause",
    invalid_client: "Check the configured OAuth client ID and client secret",
    invalid_request: "Check the request parameters, such as the code and redirectUri",
    invalid_scope: "Request only scopes that the application may use",
    unauthorized_client: "This application may not use this grant type. Check its OAuth settings",
    unsupported_grant_type: "Use a grant type that Fluxer supports",
}

/** The suggested fix for a standard OAuth error code, when the SDK has one */
function oauthErrorHint(oauthError: string | null): string | undefined {
    return oauthError !== null && Object.hasOwn(oauthErrorHints, oauthError) ? oauthErrorHints[oauthError] : undefined
}

/** Suggested fixes for rejections without a recognized code, by HTTP status */
const statusHints: Readonly<Record<number, string | undefined>> = {
    400: "Check the request parameters and body against Fluxer's requirements. Nothing was applied",
    401: apiErrorHints.unauthorized,
    403: "Check the bot's permissions and role position for this resource",
    404: apiErrorHints.unknownResource,
    405: "Check the HTTP method for this route",
    408: "The server timed out waiting for the request. Retry later",
    409: "Fetch the resource's current state and reconcile it before repeating the change",
    410: "This resource is permanently gone, so retrying does not help",
    413: "Send a smaller request body or file",
    415: "Check the request Content-Type and body format",
    422: "Check the request fields against Fluxer's validation rules",
    // Fluxer sends GENERAL_ERROR with HTTP 423 and Retry-After 2 while it holds a lock on the resource, such as a role or
    // channel reorder or a community settings update (packages/errors/src/domains/core/ResourceLockedError.ts at 5f3fc0b1)
    423: "Fluxer is applying another change to this resource, such as a role or channel reorder. Wait briefly, then send the change again",
    500: "Fluxer had a temporary server problem. Retry later",
    501: "This Fluxer server does not implement this operation, so retrying does not help",
    502: "Fluxer had a temporary server problem. Retry later",
    503: "Fluxer had a temporary server problem. Retry later",
    504: "Fluxer had a temporary server problem. Retry later",
}

/**
 * @internal The credential a request sent: The bot token, a webhook token, the OAuth client ID and secret, or an OAuth
 * user access token. A rejected credential needs a different fix for each
 */
export type RequestCredential = "bot" | "webhook" | "oauthClient" | "oauthUser"

/** The fix when Fluxer refuses a token-authenticated webhook request for a missing permission */
const webhookMessageHint = "Use a message this webhook sent. A webhook can only read, edit or delete its own messages"

/** Suggested fixes for a rejected credential other than the bot token */
const credentialHints: Readonly<Record<Exclude<RequestCredential, "bot">, string>> = {
    webhook: "Check the webhook ID and token, or recreate the webhook and use its new token",
    oauthClient: "Check the configured OAuth client ID and client secret",
    oauthUser:
        "Refresh the user's access token, or ask the user to authorize the application again. If a fresh token is also rejected, the user's account may be closed or temporarily banned, which a new token does not fix",
}

/**
 * @internal What a rejected REST route does, so a logged missing-permission hint names what that route needs.
 * Operation errors name the permissions of their operation instead
 */
export type RequestAction =
    "message" | "moderation" | "memberRole" | "unban" | "setOverwrite" | "removeOverwrite" | "other"

/** Missing-permission fixes for actions whose needs are known */
const missingPermissionHints: Readonly<Record<Exclude<RequestAction, "other">, string>> = {
    message: `Grant the bot's role ${label("ViewChannel")} and ${label("SendMessages")} in this channel, plus ${label("EmbedLinks")} or ${label("AttachFiles")} when the message has them, in the community settings or the channel's permission overrides. ${threadSend}`,
    moderation:
        "Grant the bot's role the permission this operation needs in the community settings, and move the bot's highest role above the highest role of the member it acts on",
    // Fluxer compares the bot's highest role with the role granted or removed, not with the member's roles
    memberRole: requiredPermissionsHint(permissionRequirement("members.addRole")!),
    // A refused unban and refused overwrite writes share the text of their operations, so one place owns what these routes need
    unban: requiredPermissionsHint(permissionRequirement("members.unban")!),
    setOverwrite: requiredPermissionsHint(permissionRequirement("channels.setPermissionOverwrite")!),
    removeOverwrite: requiredPermissionsHint(permissionRequirement("channels.removePermissionOverwrite")!),
}

/** @internal The action of a REST route template and HTTP method, such as GET /channels/:id/messages or DELETE /guilds/:id/bans/:id */
export function routeAction(template: string, method: string): RequestAction {
    if (template === "/channels/:id/permissions/:id") {
        if (method === "PUT") return "setOverwrite"
        if (method === "DELETE") return "removeOverwrite"
        return "other"
    }
    // Only routes whose needs are certain get a specific fix. Reads, pins, reactions, bulk deletes and role edits need
    // other permissions, so they keep the general missing-permission hint
    if (method === "POST" && template === "/channels/:id/messages") return "message"
    if (method === "DELETE" && template === "/guilds/:id/bans/:id") return "unban"
    if ((method === "PUT" || method === "DELETE") && template === "/guilds/:id/members/:id/roles/:id")
        return "memberRole"
    const memberWrite =
        ((method === "PATCH" || method === "DELETE") && template === "/guilds/:id/members/:id") ||
        (method === "PUT" && template === "/guilds/:id/bans/:id")
    return memberWrite ? "moderation" : "other"
}

/**
 * @internal Whether Fluxer refused a token-authenticated webhook request because its ID and token do not match.
 * Fluxer answers a wrong or deleted webhook token with UNKNOWN_WEBHOOK and HTTP 404, not with 401
 */
export function rejectedWebhookToken(apiError: ApiErrorDetail | null): boolean {
    return apiError?.providerCode === "UNKNOWN_WEBHOOK"
}

/** Wait-specific hint formatters when Fluxer supplied a concrete retryAfterMs delay */
const retryAfterFormatters: Readonly<Partial<Record<ApiErrorCode, (ms: number) => string>>> = {
    messageCrosspostRateLimited: (ms) => `Wait at least ${ms} ms before publishing another message in this channel`,
    publishedMessageEditRateLimited: (ms) => `Wait at least ${ms} ms before editing this published message again`,
    slowmodeRateLimited: (ms) => `Wait at least ${ms} ms for the channel's slowmode interval before sending again`,
    rateLimited: (ms) => `The request was rate-limited. Wait at least ${ms} ms before retrying`,
    resourceLocked: (ms) =>
        `Fluxer is applying another change to this resource. Wait at least ${ms} ms, then send the change again`,
}

/** Wait-specific fix when Fluxer supplied a concrete retryAfterMs delay */
function retryAfterHint(
    apiError: ApiErrorDetail | null,
    status: number | null,
    retryAfterMs: number | null,
): string | undefined {
    if (retryAfterMs === null || retryAfterMs <= 0) return undefined
    const formatter = apiError === null ? undefined : retryAfterFormatters[apiError.code]
    if (formatter !== undefined) return formatter(retryAfterMs)
    return apiError === null && status === 423
        ? `Fluxer is applying another change to this resource, such as a role or channel reorder. Wait at least ${retryAfterMs} ms, then send the change again`
        : undefined
}

/**
 * @internal The suggested fix for a Fluxer rejection, from its recognized category or else its HTTP status.
 * A rejected credential is described for the credential the request sent, which defaults to the bot token, and a
 * missing permission for the action the request tried
 */
export function apiErrorHint(
    apiError: ApiErrorDetail | null,
    status: number | null,
    credential: RequestCredential = "bot",
    actionOrOptions:
        RequestAction | { readonly action?: RequestAction; readonly retryAfterMs?: number | null } = "other",
): string | undefined {
    const action = typeof actionOrOptions === "string" ? actionOrOptions : (actionOrOptions.action ?? "other")
    const retryAfterMs = typeof actionOrOptions === "string" ? null : (actionOrOptions.retryAfterMs ?? null)
    if (credential !== "bot" && (apiError === null ? status === 401 : apiError.code === "unauthorized"))
        return credentialHints[credential]
    if (credential === "webhook" && rejectedWebhookToken(apiError)) return credentialHints.webhook
    // With a webhook token, Fluxer refuses only a message the webhook did not send this way
    // (webhook/WebhookService.ts:572, channel/services/message/MessageSendService.ts:1161 and MessageDeleteService.ts:160 at 5f3fc0b1)
    if (credential === "webhook" && apiError?.code === "missingPermissions") return webhookMessageHint
    if (apiError?.code === "missingPermissions" && action !== "other") return missingPermissionHints[action]
    if (apiError?.code === "invalidFormBody" && (apiError.validationErrors?.length ?? 0) === 0)
        return "Check the request fields against Fluxer's constraints, because Fluxer rejected the form body without naming individual fields"
    const waited = retryAfterHint(apiError, status, retryAfterMs)
    if (waited !== undefined) return waited
    const categoryHint = apiError === null ? undefined : apiErrorHints[apiError.code]
    return categoryHint ?? (status === null ? undefined : statusHints[status])
}

/** @internal Safe response facts that extend an operation-error message */
export interface OperationMessageFacts {
    /** Unrecognized Fluxer error code that matched the safe code shape */
    readonly providerCode?: string | null | undefined
    /** Response field path or named check that failed, for reason response */
    readonly responseField?: string | null | undefined
    /** Whether the request only read data, so an unknown outcome needs no mention */
    readonly read?: boolean | undefined
}

/** What each failure reason means when neither Fluxer nor local validation supplied a more specific explanation */
const reasonExplanations: Readonly<Record<string, string>> = {
    input: "The input is invalid",
    busy: "Too many requests of this kind are already pending in this client",
    network: "A network error interrupted the request",
    notFound: "Fluxer could not find the requested resource",
    rateLimit: "The request was rate-limited, and the SDK could not wait and retry it",
    rejected: "Fluxer rejected the request",
    response: "Fluxer's answer did not have the expected format",
    timeout: "The operation did not finish within its timeout",
    tooLarge: "The response is larger than the maxBytes limit",
    untrustedUrl: "The attachment URL is not on this Fluxer instance's media or API attachment path",
    notConnected: "The client is not connected to the gateway for this community",
    connectionLost: "The gateway connection was lost before Fluxer answered",
    overflow: "Unread member batches exceeded the maxPendingBytes limit",
    filter: "The selection filter threw or returned a value that is not a boolean",
    closed: "The client shut down",
}

/** Readable text for the named response checks, which are not field paths */
const responseChecks: Readonly<Record<string, string>> = {
    body: "The response body has the wrong type",
    status: "It answered with a different success status than the operation expects",
    tooMany: "It returned more items than requested",
    order: "Its items are out of order",
    channelMismatch: "The returned message belongs to a different channel",
    idMismatch: "The returned message has a different ID",
    targetMismatch: "It describes a different resource than the one requested",
}

/** @internal Describe the response field path or named check that failed, for messages and log records */
export function responseFieldText(responseField: string): string {
    return Object.hasOwn(responseChecks, responseField)
        ? (responseChecks[responseField] as string)
        : `Field ${responseField} is missing or has the wrong type`
}

/**
 * Build an operation-error message from SDK-written facts, without copying server text or unreviewed response data.
 * The message leads with the failed operation and what happened, puts Fluxer's code, the HTTP status and the retry wait
 * in parentheses, then lists rejected fields and says when a write may have been applied
 */
export function operationErrorMessage(input: {
    /** Resource or workflow named first, such as "Message cleanup" */
    readonly subject: string
    readonly operation: string
    readonly reason: string
    readonly outcome: string
    readonly status?: number | null
    readonly apiError?: ApiErrorDetail | null
    /** Explanation of a local input rejection, used when Fluxer supplied no detail */
    readonly inputExplanation?: string | null
    readonly retryAfterMs?: number | null
    readonly facts?: OperationMessageFacts
}): string {
    const { subject, operation, reason, outcome, facts = {} } = input
    const status = input.status ?? null
    const apiError = input.apiError ?? null
    const inputExplanation = input.inputExplanation ?? null
    const retryAfterMs = input.retryAfterMs ?? null
    const fallback = reasonExplanations[reason] ?? `The operation failed with reason ${reason}`
    const providerCode = facts.providerCode ?? null
    const responseField = facts.responseField ?? null
    const detail =
        apiError !== null && reason !== "rateLimit"
            ? apiError.explanation
            : providerCode !== null
              ? `Fluxer returned ${providerCode}, a code this SDK version does not describe yet`
              : reason === "response" && responseField !== null
                ? `${fallback}. ${responseFieldText(responseField)}`
                : (inputExplanation ?? fallback)
    const validation = (apiError?.validationErrors ?? []).map((error) => {
        const text =
            error.providerCode === ""
                ? error.explanation
                : Object.hasOwn(validationErrorMappings, error.providerCode)
                  ? `${error.explanation} (${error.providerCode})`
                  : `Fluxer returned ${error.providerCode}, a code this SDK version does not describe yet`
        return error.path === undefined ? text : `Field ${error.path}: ${text}`
    })
    const parts = [
        apiError?.providerCode ?? null,
        status === null ? null : `HTTP ${status}`,
        retryAfterMs === null ? null : `retry after ${retryAfterMs} ms`,
    ].filter((part): part is string => part !== null && part !== "")
    const label = operation.includes(".") ? `${subject} operation ${operation}` : `${subject} ${operation}`
    return [
        `${label} failed: ${detail}${parts.length ? ` (${parts.join(", ")})` : ""}`,
        ...validation,
        ...(outcome === "unknown" && facts.read !== true ? ["The change may still have been applied"] : []),
    ].join(". ")
}

/**
 * @internal The suggested next step for an operation failure: A possibly applied write first, then Fluxer's rejection
 * category or HTTP status, then the failure reason. An input failure names the rejected path when known, and a
 * missing permission names the permissions of a supplied requirement
 */
export function operationFailureHint(input: {
    readonly reason: string
    readonly outcome: string
    readonly status?: number | null
    readonly retryAfterMs?: number | null
    readonly apiError?: ApiErrorDetail | null
    readonly read?: boolean
    readonly streamUsed?: boolean
    readonly uploadSlotsBusy?: boolean
    readonly inputPath?: string | null | undefined
    readonly oauthError?: string | null
    readonly credential?: RequestCredential
    /** What the failed operation requires, supplied only for a missing-permission rejection */
    readonly requirement?: PermissionRequirement | undefined
}): string | undefined {
    const { reason, outcome } = input
    const read = input.read === true
    const retryAfterMs = input.retryAfterMs ?? null
    const general = operationHint(reason, outcome, retryAfterMs, {
        read,
        streamUsed: input.streamUsed === true,
    })
    if (reason === "rateLimit") {
        if (
            input.streamUsed !== true &&
            (input.apiError?.code === "messageCrosspostRateLimited" ||
                input.apiError?.code === "publishedMessageEditRateLimited" ||
                input.apiError?.code === "slowmodeRateLimited")
        )
            return apiErrorHint(input.apiError, input.status ?? null, input.credential, { retryAfterMs })
        return general
    }
    if (outcome === "unknown" && !read) return general
    // Fluxer's busy upload slots answer applied nothing and asks for another try later
    if (input.uploadSlotsBusy === true) {
        const wait = retryAfterMs !== null && retryAfterMs > 0 ? `Wait at least ${retryAfterMs} ms` : "Wait briefly"
        return input.streamUsed === true
            ? `Fluxer's upload slots were busy and nothing was applied. ${wait}, then send it again with a new stream or with the file as bytes`
            : `Fluxer's upload slots were busy and nothing was applied. ${wait}, then send it again`
    }
    if (reason === "rejected" || reason === "notFound")
        return (
            (input.requirement === undefined ? undefined : requiredPermissionsHint(input.requirement)) ??
            oauthErrorHint(input.oauthError ?? null) ??
            apiErrorHint(input.apiError ?? null, input.status ?? null, input.credential, { retryAfterMs }) ??
            (reason === "notFound" ? apiErrorHints.unknownResource : undefined)
        )
    if (reason === "input" && input.inputPath) return `Correct ${input.inputPath}. Nothing was sent to Fluxer`
    return general
}

/** @internal Normalized operation-error fields with null defaults */
export interface OperationErrorFields<
    Operation extends string,
    Reason extends string,
    Outcome extends string = OperationOutcome,
> {
    readonly operation: Operation
    readonly reason: Reason
    readonly outcome: Outcome
    readonly status: number | null
    readonly retryAfterMs: number | null
    readonly apiError: ApiErrorDetail | null
    readonly inputValidation: InputValidationDetail | null
    readonly read: boolean
    readonly streamUsed: boolean
    readonly uploadSlotsBusy: boolean
    readonly providerCode: string | null
    readonly responseField: string | null
}

/**
 * @internal Facts a composed operation keeps when it reports a failed step under its own operation name: The
 * unrecognized Fluxer code, the failing response field, the read marker and the step's error as the cause
 */
export function composedStepFacts(error: {
    readonly details: Readonly<Record<string, unknown>>
}): Pick<OperationErrorOptions<string>, "providerCode" | "responseField" | "read" | "cause"> {
    const { providerCode, responseField, read } = error.details
    return {
        providerCode: typeof providerCode === "string" ? providerCode : null,
        responseField: typeof responseField === "string" ? responseField : null,
        read: read === true,
        cause: error,
    }
}

/** @internal An unrecognized Fluxer code with the safe shape, or null. A recognized apiError wins over it */
export function safeProviderCode(apiError: ApiErrorDetail | null, providerCode: string | null): string | null {
    return apiError === null && providerCode !== null && providerCodePattern.test(providerCode) ? providerCode : null
}

/** @internal A response field path or check name with the safe shape, or null */
export function safeResponseField(responseField: string | null): string | null {
    return responseField !== null && /^[A-Za-z0-9_.]{1,128}$/.test(responseField) ? responseField : null
}

/** @internal Apply null defaults to operation-error options, keeping only safe code and field shapes */
export function operationErrorFields<Operation extends string, Reason extends string>(
    options: OperationErrorOptions<Operation, Reason>,
): OperationErrorFields<Operation, Reason> {
    const apiError = options.apiError ?? null
    const providerCode = options.providerCode ?? null
    const responseField = options.responseField ?? null
    return {
        operation: options.operation,
        reason: options.reason,
        outcome: options.outcome,
        status: options.status ?? null,
        retryAfterMs: options.retryAfterMs ?? null,
        apiError,
        inputValidation: options.inputValidation ?? null,
        read: options.read === true,
        streamUsed: options.streamUsed === true,
        uploadSlotsBusy: options.uploadSlotsBusy === true,
        providerCode: safeProviderCode(apiError, providerCode),
        responseField: safeResponseField(responseField),
    }
}

/**
 * What to say about a rejection the SDK decided itself, which Fluxer never saw. Only an operation with a local permission
 * check has an entry, so the shared text cannot claim that Fluxer rejected a request that was not sent
 */
const localRejections: Readonly<
    Record<
        string,
        {
            readonly explanation: string
            readonly hint: string
            readonly requiredPermissions?: readonly PermissionName[]
        }
    >
> = {
    "members.search": {
        explanation: `The bot needs ${label("ManageGuild")} to search by join source or invite code. The search was not sent`,
        hint: `Grant ${label("ManageGuild")} to the bot, or remove joinSourceTypes and sourceInviteCodes from this search`,
        requiredPermissions: Object.freeze(["ManageGuild"]),
    },
}

function localRejection(fields: OperationErrorFields<string, string, string>) {
    return fields.reason === "rejected" &&
        fields.outcome === "notDispatched" &&
        fields.apiError === null &&
        Object.hasOwn(localRejections, fields.operation)
        ? localRejections[fields.operation]
        : undefined
}

/** @internal The readable message for a resource operation error */
export function operationErrorText(subject: string, fields: OperationErrorFields<string, string, string>): string {
    return operationErrorMessage({
        subject,
        operation: fields.operation,
        reason: fields.reason,
        outcome: fields.outcome,
        status: fields.status,
        apiError: fields.apiError,
        inputExplanation: fields.inputValidation?.explanation ?? localRejection(fields)?.explanation ?? null,
        retryAfterMs: fields.retryAfterMs,
        facts: fields,
    })
}

/**
 * @internal Code, hint, cause and safe details for a resource operation error. A missing-permission rejection of an
 * operation with a known requirement names its permissions in the hint and in details.requiredPermissions
 */
export function operationErrorSettings(
    prefix: string,
    fields: OperationErrorFields<string, string, string>,
    cause: unknown,
    credential: RequestCredential = "bot",
): FluxerlyErrorOptions {
    const local = localRejection(fields)
    const requirement =
        fields.apiError?.code === "missingPermissions" ? permissionRequirement(fields.operation) : undefined
    return {
        code: `${prefix}.${fields.reason}`,
        hint:
            local?.hint ??
            operationFailureHint({
                ...fields,
                inputPath: fields.inputValidation?.path ?? null,
                credential,
                requirement,
            }),
        cause,
        details: operationDetails({
            operation: fields.operation,
            reason: fields.reason,
            outcome: fields.outcome,
            status: fields.status,
            retryAfterMs: fields.retryAfterMs,
            apiError: fields.apiError?.providerCode,
            apiCode: fields.apiError?.code,
            providerCode: fields.providerCode,
            responseField: fields.responseField,
            inputPath: fields.inputValidation?.path,
            inputConstraint: fields.inputValidation?.constraint,
            read: fields.read || undefined,
            streamUsed: fields.streamUsed || undefined,
            uploadSlotsBusy: fields.uploadSlotsBusy || undefined,
            requiredPermissions: local?.requiredPermissions ?? requirement?.permissions,
        }),
    }
}