import type { ImagePack, PackImage } from './types';

export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;

export interface StagedAttachment {
  id: number;
  file: File;
  previewUrl: string | null;
}

export interface StickerHandlers {
  onSend: (pack: ImagePack, image: PackImage) => void;
  onClone: (pack: ImagePack, image: PackImage, x: number, y: number) => void;
  onClonePack: (pack: ImagePack, x: number, y: number) => void;
  onManage: () => void;
  roomName: (roomId: string) => string;
}

let nextId = 1;

/** Files outside the homeserver-friendly size range are reported through `reject` and skipped. */
export function stageFiles(files: File[], reject: (message: string) => void): StagedAttachment[] {
  const accepted: StagedAttachment[] = [];
  for (const file of files) {
    if (file.size === 0 || file.size > MAX_ATTACHMENT_BYTES) {
      reject(`${file.name || 'File'} must be between 1 byte and 20 MiB.`);
      continue;
    }
    accepted.push({ id: nextId++, file, previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : null });
  }
  return accepted;
}

export function releaseStaged(list: StagedAttachment[]): void {
  for (const attachment of list) if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl);
}
