import { apiClient } from './api-client';

// ─── Types ──────────────────────────────────────────────

export interface InquiryReadDto {
  id: string;
  listingId: string;
  listingTitle: string;
  userId: string;
  userName: string;
  userPhone: string;
  message: string;
  phone: string | null;
  isRead: boolean;
  createdAt: string;
}

export interface CreateInquiryDto {
  listingId: string;
  message: string;
  phone: string;
}

export interface PaginatedResult<T> {
  data: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export interface ListInquiriesParams {
  page?: number;
  limit?: number;
}

// ─── API Functions ──────────────────────────────────────

export const inquiriesApi = {
  /** List all inquiries for current agent */
  getMyInquiries: (params: ListInquiriesParams = {}) => {
    const query = new URLSearchParams();
    if (params.page) query.append('page', String(params.page));
    if (params.limit) query.append('limit', String(params.limit));
    const qs = query.toString();
    return apiClient.get<PaginatedResult<InquiryReadDto>>(
      `/inquiries/agent/me${qs ? `?${qs}` : ''}`,
    );
  },

  /** List inquiries by listing */
  getByListing: (listingId: string, params: ListInquiriesParams = {}) => {
    const query = new URLSearchParams();
    if (params.page) query.append('page', String(params.page));
    if (params.limit) query.append('limit', String(params.limit));
    const qs = query.toString();
    return apiClient.get<PaginatedResult<InquiryReadDto>>(
      `/inquiries/listing/${listingId}${qs ? `?${qs}` : ''}`,
    );
  },

  /** Mark an inquiry as read */
  markAsRead: (id: string) =>
    apiClient.patch<{ success: boolean }>(`/inquiries/${id}/read`),

  /** Create a new inquiry for a listing */
  create: (data: CreateInquiryDto) =>
    apiClient.post<InquiryReadDto>('/inquiries', data),
};
