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

export interface ContactMessage {
  id: string;
  name: string;
  email: string;
  subject?: string;
  message: string;
  source?: string;
  ipAddress?: string;
  userAgent?: string;
  isRead: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface ContactMessagesResponse {
  data: ContactMessage[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export const getContactMessages = async (params?: {
  page?: number;
  limit?: number;
  search?: string;
  isRead?: boolean;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}): Promise<ContactMessagesResponse> => {
  // Backend returns { data: ContactMessage[], pagination: { total, page, limit, pages, has_more } }
  const response = await api.get<{ data: ContactMessage[]; pagination: { total: number; page: number; limit: number; pages: number } }>(
    '/admin/contact-messages',
    { params }
  );
  const r = response.data;
  // Normalize possible snake_case fields coming from backend to camelCase expected by UI
  const normalized = (r.data as any[]).map((m) => ({
    id: String(m.id),
    name: m.name,
    email: m.email,
    subject: m.subject,
    message: m.message,
    source: m.source,
    ipAddress: m.ipAddress ?? m.ip_address,
    userAgent: m.userAgent ?? m.user_agent,
    isRead: m.isRead ?? m.is_read ?? false,
    createdAt: m.createdAt ?? m.created_at,
    updatedAt: m.updatedAt ?? m.updated_at,
  })) as ContactMessage[];
  return {
    data: normalized,
    total: r.pagination.total,
    page: r.pagination.page,
    limit: r.pagination.limit,
    totalPages: r.pagination.pages,
  };
};

export const getContactMessage = async (id: string) => {
  // Backend returns the message object directly
  const response = await api.get<ContactMessage>(`/admin/contact-messages/${id}`);
  return response.data;
};

export const markAsRead = async (id: string) => {
  // Backend returns only a message string; caller doesn't need data
  await api.patch(
    `/admin/contact-messages/${id}/read`,
    { isRead: true }
  );
};

export const deleteMessage = async (id: string) => {
  await api.delete(`/admin/contact-messages/${id}`);
};

export const deleteMultipleMessages = async (ids: Array<string | number>) => {
  // Backend expects a raw JSON array []int in the body. Convert to numbers.
  const numericIds = ids.map((v) => (typeof v === 'string' ? Number(v) : v));
  await api.delete('/admin/contact-messages', { data: numericIds });
};

export const forwardMessage = async (id: string, toEmail: string) => {
  await api.post(`/admin/contact-messages/${id}/forward`, { to_email: toEmail });
};

export const forwardAllMessages = async (toEmail: string) => {
  const response = await api.post('/admin/contact-messages/forward-all', { to_email: toEmail });
  return response.data;
};
