/** Guildly bot SDK. Node 22 or later. */
/// <reference types="node" />

import { EventEmitter } from "node:events";

/** Ids are decimal strings. */
export type Snowflake = string;

export interface EmbedField {
  /** Up to 256 characters. */
  name: string;
  /** Up to 1024 characters. */
  value: string;
  inline?: boolean;
}

export interface Embed {
  /** Up to 256 characters. */
  title?: string;
  /** Up to 4096 characters. */
  description?: string;
  /** https only. */
  url?: string;
  /** 0 to 0xFFFFFF. */
  color?: number;
  /** Up to 25. */
  fields?: EmbedField[];
  footer?: { text: string };
  /** An `/attachments/<id>` of this service, or an allowed GIPHY media address. */
  imageUrl?: string;
  /** As imageUrl. */
  thumbnailUrl?: string;
  /** ISO 8601. */
  timestamp?: string;
}

export type Button =
  | {
      type: "button";
      style: "primary" | "secondary" | "success" | "danger";
      /** Up to 80 characters. */
      label: string;
      /** Up to 100 characters, unique in the message. */
      customId: string;
      disabled?: boolean;
    }
  | { type: "button"; style: "link"; label: string; url: string; disabled?: boolean };

export interface SelectOption {
  label: string;
  value: string;
  description?: string;
}

export interface Select {
  type: "select";
  customId: string;
  /** Up to 150 characters. */
  placeholder?: string;
  minValues?: number;
  maxValues?: number;
  disabled?: boolean;
  /** 1 to 25. */
  options: SelectOption[];
}

/** One to five buttons, or one select menu. */
export interface ActionRow {
  components: Button[] | [Select];
}

/** At least one of content, embeds and components. */
export interface MessageBody {
  content?: string;
  /** Up to 10, 6000 characters of text in all. */
  embeds?: Embed[];
  /** Up to 5 rows. */
  components?: ActionRow[];
  replyToId?: Snowflake;
}

export interface InteractionReplyBody {
  content?: string;
  embeds?: Embed[];
  components?: ActionRow[];
  /** Shown only to the person who used it. Ephemeral messages take no components. */
  ephemeral?: boolean;
}

export type CommandOptionType =
  | "string"
  | "integer"
  | "number"
  | "boolean"
  | "user"
  | "channel"
  | "role";

export interface CommandOption {
  name: string;
  description: string;
  type: CommandOptionType;
  /** Required options come first. */
  required?: boolean;
  /** string, integer and number only; up to 25. */
  choices?: { name: string; value: string | number }[];
}

export interface CommandDefinition {
  /** 1 to 32 of a-z, 0-9, "_" and "-". */
  name: string;
  /** 1 to 100 characters. */
  description: string;
  /** Up to 25. */
  options?: CommandOption[];
}

export interface Command extends CommandDefinition {
  id: Snowflake;
  applicationId: Snowflake;
  guildId: Snowflake | null;
  options: CommandOption[];
}

export interface BotIdentity {
  application: {
    id: Snowflake;
    botUserId: Snowflake;
    name: string;
    handle: string;
    description: string;
    public: boolean;
    avatarId: Snowflake | null;
    createdAt?: string;
    lastUsedAt?: string | null;
  };
  user: { id: Snowflake; username: string; discriminator: string };
  guilds: Snowflake[];
}

export interface RequestOptions {
  body?: unknown;
  query?: Record<string, string | number | boolean | null | undefined>;
  /** Send the bot token. Default true. */
  auth?: boolean;
  /** How many times to retry a 429. */
  retries?: number;
  /** Longest retry-after worth waiting for; longer ones throw. */
  maxRetryAfterMs?: number;
}

export interface Rest {
  request<T = any>(method: string, path: string, options?: RequestOptions): Promise<T>;
  get<T = any>(path: string, options?: RequestOptions): Promise<T>;
  post<T = any>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
  put<T = any>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
  patch<T = any>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
  delete<T = any>(path: string, options?: RequestOptions): Promise<T>;
}

export class GuildlyError extends Error {
  status?: number;
  code?: string;
  retryAfter?: number;
  method?: string;
  path?: string;
  body?: unknown;
  closeCode?: number;
}

export class Message {
  private constructor();
  id: Snowflake;
  channelId: Snowflake;
  authorId: Snowflake | null;
  authorHandle?: string | null;
  authorBot: boolean;
  author: { id: Snowflake | null; handle: string | null; bot: boolean };
  content: string;
  embeds: Embed[];
  components: ActionRow[];
  replyToId: Snowflake | null;
  createdAt: string;
  editedAt?: string | null;
  interaction?: {
    id: Snowflake;
    /** Left out for buttons and select menus. */
    commandName?: string;
    userId: Snowflake;
    userHandle: string;
  };
  ephemeral: boolean;
  reply(body: string | MessageBody): Promise<Message>;
  edit(body: string | MessageBody): Promise<Message>;
  delete(): Promise<void>;
  react(emoji: string): Promise<void>;
  unreact(emoji: string): Promise<void>;
  pin(): Promise<void>;
  unpin(): Promise<void>;
}

export type OptionValue = string | number | boolean;

export class InteractionOptions {
  /** The value given, or null when the option was left out. */
  get<T extends OptionValue = OptionValue>(name: string): T | null;
  has(name: string): boolean;
  toJSON(): Record<string, OptionValue>;
}

export class Interaction {
  private constructor();
  id: Snowflake;
  applicationId: Snowflake;
  type: "command" | "component";
  guildId: Snowflake;
  channelId: Snowflake;
  user: { id: Snowflake; username: string; discriminator: string; handle: string };
  memberRoles: Snowflake[];
  /** Permission bitfield as a decimal string. */
  memberPermissions: string;
  commandId: Snowflake | null;
  commandName: string | null;
  options: InteractionOptions;
  customId: string | null;
  componentType: "button" | "select" | null;
  /** Chosen values of a select menu. */
  values: string[];
  /** The message a button or select menu is on. */
  message: Message | null;
  isCommand(): boolean;
  isComponent(): boolean;
  isButton(): boolean;
  isSelect(): boolean;
  hasPermission(bits: bigint | string): boolean;
  reply(body: string | InteractionReplyBody): Promise<Message | null>;
  defer(options?: { ephemeral?: boolean }): Promise<Message | null>;
  update(body: string | InteractionReplyBody): Promise<Message | null>;
  deferUpdate(): Promise<Message | null>;
  followUp(body: string | InteractionReplyBody): Promise<Message | null>;
  editReply(body: string | Omit<InteractionReplyBody, "ephemeral">): Promise<Message | null>;
}

export interface ClientOptions {
  /** Give both addresses, or neither for the live service. */
  baseUrl?: string;
  gatewayUrl?: string;
  reconnect?: {
    baseDelayMs?: number;
    maxDelayMs?: number;
    rateLimitDelayMs?: number;
    connectTimeoutMs?: number;
  };
  rest?: { retries?: number; timeoutMs?: number; maxRetryAfterMs?: number };
}

export interface ClientEvents {
  ready: [client: Client];
  messageCreate: [message: Message];
  messageUpdate: [message: Message];
  messageDelete: [data: { id: Snowflake; channelId: Snowflake; guildId: Snowflake | null }];
  interactionCreate: [interaction: Interaction];
  raw: [type: string, data: any];
  disconnect: [info: { code: number; reason: string; willReconnect: boolean }];
  resumed: [];
  reconnected: [info: { resumed: boolean }];
  error: [error: Error];
}

export class Client extends EventEmitter {
  constructor(options?: ClientOptions);
  user: { id: Snowflake } | null;
  application: { id: Snowflake } | null;
  guildIds: Set<Snowflake>;
  readonly rest: Rest;
  readonly channels: {
    send(channelId: Snowflake, body: string | MessageBody): Promise<Message>;
    /** Newest first. */
    history(channelId: Snowflake, options?: { limit?: number; before?: Snowflake }): Promise<Message[]>;
    typing(channelId: Snowflake): Promise<void>;
  };
  readonly commands: {
    list(guildId?: Snowflake | null): Promise<Command[]>;
    /** Replaces the whole set. */
    set(commands: CommandDefinition[], guildId?: Snowflake | null): Promise<Command[]>;
  };
  readonly attachments: {
    upload(file: { filename: string; contentType: string; data: Uint8Array }): Promise<{
      id: Snowflake;
      filename: string;
      contentType: string;
      byteSize: number;
      url: string;
    }>;
  };
  setToken(token: string): this;
  login(token: string): Promise<this>;
  destroy(): void;
  me(): Promise<BotIdentity>;

  on<E extends keyof ClientEvents>(event: E, listener: (...args: ClientEvents[E]) => void): this;
  on(event: string, listener: (...args: any[]) => void): this;
  once<E extends keyof ClientEvents>(event: E, listener: (...args: ClientEvents[E]) => void): this;
  once(event: string, listener: (...args: any[]) => void): this;
}
