import api from './api';
import type {
  Conversation,
  Message,
  MessagesResponse,
  CreateMessageDto,
} from '@/types/messaging';

interface ApiResponse<T> {
  success: boolean;
  data: T;
  timestamp: string;
}

class MessagesService {
  /**
   * Get all conversations for the current user
   */
  async getConversations(): Promise<Conversation[]> {
    const response = await api.get<ApiResponse<Conversation[]>>('/messages/conversations');
    return response.data.data;
  }

  /**
   * Start or get existing conversation with an agent (for users) or a user (for agents)
   */
  async startConversation(body: { agentProfileId?: string; userId?: string }): Promise<Conversation> {
    const response = await api.post<ApiResponse<Conversation>>('/messages/conversations', body);
    return response.data.data;
  }

  /**
   * Get a specific conversation
   */
  async getConversation(conversationId: string): Promise<Conversation> {
    const response = await api.get<ApiResponse<Conversation>>(
      `/messages/conversations/${conversationId}`
    );
    return response.data.data;
  }

  /**
   * Get messages for a conversation with pagination
   */
  async getMessages(
    conversationId: string,
    page: number = 1,
    limit: number = 50
  ): Promise<MessagesResponse> {
    const response = await api.get<ApiResponse<MessagesResponse>>(
      `/messages/conversations/${conversationId}/messages`,
      { params: { page, limit } }
    );
    return response.data.data;
  }

  /**
   * Send a message via REST API (fallback for WebSocket)
   */
  async sendMessage(conversationId: string, dto: CreateMessageDto): Promise<Message> {
    const response = await api.post<ApiResponse<Message>>(
      `/messages/conversations/${conversationId}/messages`,
      dto
    );
    return response.data.data;
  }

  /**
   * Mark all messages in a conversation as read
   */
  async markAsRead(conversationId: string): Promise<void> {
    await api.patch(`/messages/conversations/${conversationId}/read`);
  }

  /**
   * Clear all messages in a conversation (keep the conversation)
   */
  async clearChat(conversationId: string): Promise<void> {
    await api.delete(`/messages/conversations/${conversationId}/messages`);
  }

  /**
   * Delete a conversation
   */
  async deleteConversation(conversationId: string): Promise<void> {
    await api.delete(`/messages/conversations/${conversationId}`);
  }

  /**
   * Get total unread message count
   */
  async getUnreadCount(): Promise<number> {
    const response = await api.get<ApiResponse<{ unreadCount: number }>>('/messages/unread-count');
    return response.data.data.unreadCount;
  }

  /**
   * Toggle mute status for a conversation
   */
  async toggleMute(conversationId: string, muted: boolean): Promise<void> {
    await api.patch(`/messages/conversations/${conversationId}/mute`, { muted });
  }

  /**
   * Toggle favorite/star status for a conversation
   */
  async toggleFavorite(conversationId: string, favorited: boolean): Promise<void> {
    await api.patch(`/messages/conversations/${conversationId}/favorite`, { favorited });
  }
}

export const messagesService = new MessagesService();
