// Backend-agnostic API surface. Every call forwards to whichever transport
// this build was compiled for, hosted (fetch + SSE) or on-device (worker).
import type { EventContext, EventContextPage, MemberSummary, RoomSummary } from './types';
import type { Emote } from './emotes';
import { formatBody } from './markdown';
import { mentionedUserIds, type Mention } from './mentions';
import { HttpTransport } from './transport-http';
import type { CommandRequest, SendKind, SessionInfo, Transport, VerifyAction } from './transport';
import { createDeviceTransport } from 'malice:device-transport';

export { ApiError } from './transport';
export type { SessionInfo, SoftLogout, VerifyAction } from './transport';

function createTransport(): Transport {
  if (import.meta.env.VITE_MALICE_TARGET === 'device') return createDeviceTransport();
  return new HttpTransport();
}

const transport: Transport = createTransport();

export function getSession(): Promise<SessionInfo> {
  return transport.getSession();
}

export function login(homeserver: string, username: string, password: string): Promise<{ user_id: string }> {
  return transport.login(homeserver, username, password);
}

export function logout(): Promise<void> {
  return transport.logout();
}

export function getRooms(): Promise<{ rooms: RoomSummary[] }> {
  return transport.getRooms();
}

export const openRoom = (room_id: string) => transport.openRoom(room_id);
export const closeRoom = (room_id: string) => transport.closeRoom(room_id);
export const sendMessage = (
  room_id: string,
  body: string,
  reply_to: string | null = null,
  mentions: Mention[] = [],
  kind: SendKind = 'text',
  emotes: Emote[] = []
) => transport.sendMessage(room_id, body, formatBody(body, mentions, true, emotes), reply_to, mentionedUserIds(mentions), kind);
export const runCommand = (request: CommandRequest) => transport.command(request);
export const uploadAvatar = (file: File) => transport.uploadAvatar(file);
export const uploadRoomAvatar = (room_id: string, file: File) => transport.uploadRoomAvatar(room_id, file);
export const uploadMedia = (file: File) => transport.uploadMedia(file);
export const paginateRoom = (room_id: string) => transport.paginateRoom(room_id);
export const eventContext = (room_id: string, event_id: string, limit?: number): Promise<EventContext> =>
  transport.eventContext(room_id, event_id, limit);
export const eventContextBefore = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
  transport.eventContextBefore(room_id, event_id, from, limit);
export const eventContextAfter = (room_id: string, event_id: string, from: string, limit?: number): Promise<EventContextPage> =>
  transport.eventContextAfter(room_id, event_id, from, limit);
export const setTyping = (room_id: string, typing: boolean) => transport.setTyping(room_id, typing);
export const getAccountData = (eventType: string) => transport.getAccountData(eventType);
export const getUrlPreview = (room_id: string, url: string) => transport.getUrlPreview(room_id, url);
export const setAccountData = (eventType: string, content: Record<string, unknown>) =>
  transport.setAccountData(eventType, content);

export function joinRoom(room: string): Promise<{ room_id: string }> {
  return transport.joinRoom(room);
}

export function createRoom(name: string, topic?: string): Promise<{ room_id: string }> {
  return transport.createRoom(name, topic);
}

export const leaveRoom = (room_id: string) => transport.leaveRoom(room_id);
export const reactToMessage = (room_id: string, event_id: string, key: string, shortcode?: string) =>
  transport.reactToMessage(room_id, event_id, key, shortcode);
export const editMessage = (room_id: string, event_id: string, body: string, mentions: Mention[] = [], emotes: Emote[] = []) =>
  transport.editMessage(room_id, event_id, body, formatBody(body, mentions, true, emotes), mentionedUserIds(mentions));
export const markRead = (room_id: string, event_id: string) => transport.markRead(room_id, event_id);

export function getMembers(room_id: string): Promise<{ members: MemberSummary[] }> {
  return transport.getMembers(room_id);
}

/** Same URL shape in both builds: the hosted server and the device service worker both answer it. */
export function mediaUrl(mxc: string | null): string | null {
  if (!mxc) return null;
  return `/api/media?mxc=${encodeURIComponent(mxc)}`;
}

export function messageMediaUrl(mediaId: string, size: 'Thumbnail' | 'Full'): string {
  return `/api/message-media?media_id=${encodeURIComponent(mediaId)}&size=${size}`;
}

export function getProfile(): Promise<{ display_name: string | null; avatar_url: string | null }> {
  return transport.getProfile();
}

export function getSpaceChildren(room_id: string): Promise<{ room_ids: string[] }> {
  return transport.getSpaceChildren(room_id);
}

export function getEncryption(): Promise<{ state: unknown; verification: unknown }> {
  return transport.getEncryption();
}

export function recoverEncryption(recovery_key: string): Promise<void> {
  return transport.recoverEncryption(recovery_key);
}

export function startVerification(): Promise<void> {
  return transport.startVerification();
}

export function verifyEncryption(action: VerifyAction): Promise<void> {
  return transport.verifyEncryption(action);
}

export function uploadAttachment(
  room_id: string,
  file: File,
  caption: string | null = null,
  reply_to: string | null = null,
  mentions: Mention[] = [],
  emotes: Emote[] = []
): Promise<void> {
  return transport.uploadAttachment(room_id, file, {
    caption,
    formatted_caption: caption ? formatBody(caption, mentions, true, emotes) : null,
    reply_to,
    mentions: mentionedUserIds(mentions)
  });
}

export function subscribeEvents(onEvent: (data: string) => void, onDisconnect: () => void): () => void {
  return transport.subscribeEvents(onEvent, onDisconnect);
}
