import api, { ApiResponse } from './api';

interface SupportChat {
  id: string;
  userId: string;
  status: 'OPEN' | 'CLOSED';
  lastMessageAt: string | null;
  lastMessageText: string | null;
  userUnreadCount: number;
  adminUnreadCount: number;
  createdAt: string;
  updatedAt: string;
  user: {
    id: string;
    email: string;
    role: string;
    userProfile: { firstName: string | null; lastName: string | null; avatar: string | null } | null;
    agentProfile: { firstName: string | null; lastName: string | null; avatar: string | null } | null;
  };
}

interface SupportMessage {
  id: string;
  chatId: string;
  senderId: string;
  senderRole: string;
  content: string;
  createdAt: string;
}

interface MessagesResponse {
  messages: SupportMessage[];
  pagination: { page: number; limit: number; total: number; pages: number };
}

class SupportChatService {
  async getAllChats(status?: string): Promise<SupportChat[]> {
    const params = status ? { status } : {};
    const response = await api.get<ApiResponse<SupportChat[]>>('/support-chat/admin/all', { params });
    return response.data.data;
  }

  async getMessages(chatId: string, page = 1): Promise<MessagesResponse> {
    const response = await api.get<ApiResponse<MessagesResponse>>(`/support-chat/${chatId}/messages`, { params: { page, limit: 50 } });
    return response.data.data;
  }

  async sendMessage(chatId: string, content: string): Promise<SupportMessage> {
    const response = await api.post<ApiResponse<SupportMessage>>(`/support-chat/${chatId}/messages`, { content });
    return response.data.data;
  }

  async markAsRead(chatId: string): Promise<void> {
    await api.patch(`/support-chat/${chatId}/read`);
  }

  async closeChat(chatId: string): Promise<SupportChat> {
    const response = await api.patch<ApiResponse<SupportChat>>(`/support-chat/admin/${chatId}/close`);
    return response.data.data;
  }

  async getUnreadTotal(): Promise<number> {
    const response = await api.get<ApiResponse<number>>('/support-chat/admin/unread-total');
    return response.data.data;
  }
}

export const supportChatService = new SupportChatService();
export type { SupportChat, SupportMessage, MessagesResponse };
