import type { AlqoveClient } from '../client';
import type { MyThreadsResponse } from './me';

export interface MessageAttachment {
  url: string;
  thumb_url: string;
  content_type: string;
  size_bytes: number;
}

export interface MessageAttachmentUpload {
  id: string;
  url: string;
  content_type: string;
  size_bytes: number;
}

export interface Message {
  id: string;
  thread_id: string;
  author_user_id: string | null;
  author_role: 'buyer' | 'seller' | 'admin' | 'system';
  body: string | null;
  attachments: MessageAttachment[];
  created_at: string;
  deleted_at: string | null;
  deleted_by_user_id: string | null;
  deleted_by_admin: boolean;
}

export interface MessageList {
  data: Message[];
  meta: { total: number; has_more: boolean };
}

export interface PostMessageBody {
  body: string;
  attachment_ids?: string[];
}

export interface MessageResponse {
  data: Message;
}

export interface AttachmentUploadResponse {
  data: MessageAttachmentUpload;
}

export function createMessageEndpoints(client: AlqoveClient) {
  return {
    forStore(storeId: string) {
      const base = `/v1/stores/${storeId}`;
      return {
        threads: () => client.get<MyThreadsResponse>(`${base}/threads`),
        list: (orderId: string) => client.get<MessageList>(`${base}/orders/${orderId}/messages`),
        post: (orderId: string, body: PostMessageBody) => client.post<MessageResponse>(`${base}/orders/${orderId}/messages`, body),
        delete: (messageId: string) => client.delete<void>(`${base}/messages/${messageId}`),
        uploadAttachment(orderId: string, file: File) {
          const fd = new FormData();
          fd.append('file', file);
          return client.postFormData<AttachmentUploadResponse>(`${base}/orders/${orderId}/messages/attachments`, fd);
        },
      };
    },
    list(orderId: string) {
      return client.get<MessageList>(`/v1/orders/${orderId}/messages`);
    },
    post(orderId: string, body: PostMessageBody) {
      return client.post<MessageResponse>(`/v1/orders/${orderId}/messages`, body);
    },
    delete(messageId: string) {
      return client.delete<void>(`/v1/messages/${messageId}`);
    },
    uploadAttachment(orderId: string, file: File) {
      const fd = new FormData();
      fd.append('file', file);
      return client.postFormData<AttachmentUploadResponse>(
        `/v1/orders/${orderId}/messages/attachments`,
        fd,
      );
    },
  };
}
