/**
 * Chat Service
 * Handles chat-related API calls
 */

import { apiClient } from '../client'
import type { ContactType, ChatType, ProfileUserType, UserChatType } from '@/types/apps/chatTypes'

export interface GetContactsResponse {
  contacts: ContactType[]
}

export interface GetChatConversationsResponse {
  chats: ChatType[]
}

export interface GetChatMessagesResponse {
  messages: UserChatType[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

export interface SendChatMessageRequest {
  message: string
}

export interface SendChatMessageResponse {
  message: UserChatType & {
    id: number
  }
}

export interface MarkMessageAsReadResponse {
  success: boolean
}

export interface GetProfileResponse {
  profileUser: ProfileUserType
}

export const chatService = {
  /**
   * دریافت لیست مخاطبین
   */
  async getContacts(): Promise<ContactType[]> {
    const response = await apiClient.get<GetContactsResponse>('/api/chat/contacts')
    return response.contacts || []
  },

  /**
   * دریافت چت‌های کاربر
   */
  async getConversations(): Promise<ChatType[]> {
    const response = await apiClient.get<GetChatConversationsResponse>('/api/chat/conversations')
    return response.chats || []
  },

  /**
   * دریافت پیام‌های چت
   */
  async getMessages(
    conversationId: number,
    page?: number,
    limit?: number
  ): Promise<{ messages: UserChatType[]; pagination: GetChatMessagesResponse['pagination'] }> {
    const params = new URLSearchParams()
    if (page !== undefined) params.append('page', page.toString())
    if (limit !== undefined) params.append('limit', limit.toString())

    const queryString = params.toString()
    const endpoint = `/api/chat/conversations/${conversationId}/messages${queryString ? `?${queryString}` : ''}`

    const response = await apiClient.get<GetChatMessagesResponse>(endpoint)
    return {
      messages: response.messages || [],
      pagination: response.pagination
    }
  },

  /**
   * ارسال پیام جدید
   */
  async sendMessage(conversationId: number, message: string): Promise<UserChatType & { id: number }> {
    const response = await apiClient.post<SendChatMessageResponse>(
      `/api/chat/conversations/${conversationId}/messages`,
      { message }
    )
    return response.message
  },

  /**
   * به‌روزرسانی وضعیت مشاهده پیام
   */
  async markMessageAsRead(messageId: number): Promise<boolean> {
    const response = await apiClient.put<MarkMessageAsReadResponse>(`/api/chat/messages/${messageId}/read`)
    return response.success
  },

  /**
   * دریافت اطلاعات پروفایل کاربر
   */
  async getProfile(): Promise<ProfileUserType> {
    const response = await apiClient.get<GetProfileResponse>('/api/chat/profile')
    return response.profileUser
  }
}




