import api from './api';

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

export interface SupportChat {
  id: string;
  userId: string;
  status: 'OPEN' | 'CLOSED';
  lastMessageAt: string | null;
  lastMessageText: string | null;
  userUnreadCount: number;
  adminUnreadCount: number;
  createdAt: string;
  updatedAt: string;
}

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

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

class SupportChatService {
  async getOrCreateChat(): Promise<SupportChat> {
    const response = await api.post<ApiResponse<SupportChat>>('/support-chat');
    return response.data.data;
  }

  async getMyChat(): Promise<SupportChat> {
    const response = await api.get<ApiResponse<SupportChat>>('/support-chat/my');
    return response.data.data;
  }

  async getMessages(chatId: string, page = 1): Promise<SupportMessagesResponse> {
    const response = await api.get<ApiResponse<SupportMessagesResponse>>(
      `/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`);
  }
}

export const supportChatService = new SupportChatService();
