import type { ChatImageAttachment } from '@easyflow/common-ui';

import { api } from '#/api/request';

export type AgentComposerMode = 'DRAFT' | 'FORMAL';

export interface AgentMediaUpload extends ChatImageAttachment {
  expiresAt?: string;
  height: number;
  mimeType: string;
  name: string;
  previewUrl: string;
  size: number;
  uploadId: string;
  width: number;
}

export interface AgentComposerDraftPayload {
  agentId: string;
  expiresAt?: string;
  imageUploadIds: string[];
  images?: AgentMediaUpload[];
  mode: AgentComposerMode;
  revision: number;
  sessionId: string;
  text: string;
}

interface RequestResult<T = any> {
  data: T;
  errorCode: number;
  message?: string;
}

export function allocateAgentComposerSession(mode: AgentComposerMode) {
  return api.post<
    RequestResult<{ mode: AgentComposerMode; sessionId: string }>
  >('/api/v1/agent/composer/session', { mode });
}

export function uploadAgentChatImage(
  file: File,
  context: {
    agentId: string;
    mode: AgentComposerMode;
    sessionId: string;
  },
) {
  const body = new FormData();
  body.append('file', file);
  body.append('mode', context.mode);
  body.append('agentId', context.agentId);
  body.append('sessionId', context.sessionId);
  return api.postFile<RequestResult<AgentMediaUpload>>(
    '/api/v1/agent/media/upload',
    body,
  );
}

export function deleteAgentChatImage(uploadId: string) {
  return api.post<RequestResult<void>>('/api/v1/agent/media/delete', {
    uploadId,
  });
}

export function getAgentComposerDraft(params: {
  agentId: string;
  mode: AgentComposerMode;
  sessionId?: string;
}) {
  return api.get<RequestResult<AgentComposerDraftPayload | null>>(
    '/api/v1/agent/composer/draft',
    { params },
  );
}

export function saveAgentComposerDraft(data: AgentComposerDraftPayload) {
  return api.post<RequestResult<AgentComposerDraftPayload>>(
    '/api/v1/agent/composer/draft/persist',
    data,
  );
}

export function deleteAgentComposerDraft(data: {
  agentId: string;
  deleteUploads?: boolean;
  imageUploadIds?: string[];
  mode: AgentComposerMode;
  sessionId: string;
}) {
  return api.post<RequestResult<void>>(
    '/api/v1/agent/composer/draft/delete',
    data,
  );
}

export async function loadAgentChatImage(previewUrl: string) {
  if (!previewUrl || /^(blob:|data:)/i.test(previewUrl)) return previewUrl;
  const blob = await api.download<Blob>(previewUrl);
  return URL.createObjectURL(blob);
}
