import apiClient from '../../../shared/services/apiClient';

export interface ReportData {
  total_bookings: number;
  total_revenue: number;
  total_customers: number;
  available_rooms: number;
  occupied_rooms: number;
  total_payments?: number;
  total_invoices?: number;
  total_rooms?: number;
  active_bookings?: number;
  pending_payments?: number;
  revenue_by_date?: Array<{
    date: string;
    revenue: number;
    bookings: number;
  }>;
  bookings_by_status?: {
    pending: number;
    confirmed: number;
    checked_in: number;
    checked_out: number;
    cancelled: number;
  };
  top_rooms?: Array<{
    room_id: number;
    room_number: string;
    bookings: number;
    revenue: number;
  }>;
  service_usage?: Array<{
    service_id: number;
    service_name: string;
    usage_count: number;
    total_revenue: number;
  }>;
}

export interface ReportResponse {
  success: boolean;
  status?: string;
  data: ReportData;
  message?: string;
}

export interface ReportParams {
  from?: string;
  to?: string;
  type?: 'daily' | 'weekly' | 'monthly' | 'yearly';
}

export const getReports = async (
  params: ReportParams = {}
): Promise<ReportResponse> => {
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>('/reports', { params });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    status: data.status,
    data: (data.data as ReportData) || {
      total_bookings: 0,
      total_revenue: 0,
      total_customers: 0,
      available_rooms: 0,
      occupied_rooms: 0,
    },
    message: data.message,
  };
};

export const getDashboardStats = async (): Promise<ReportResponse> => {
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>('/reports/dashboard');
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    success: data.status === 'success' || data.success === true,
    status: data.status,
    data: (data.data as ReportData) || {
      total_bookings: 0,
      total_revenue: 0,
      total_customers: 0,
      available_rooms: 0,
      occupied_rooms: 0,
    },
    message: data.message,
  };
};

export const exportReport = async (
  params: ReportParams = {}
): Promise<Blob> => {
  const response = await apiClient.get('/reports/export', {
    params,
    responseType: 'blob',
  });
  return response.data;
};

export default {
  getReports,
  getDashboardStats,
  exportReport,
};
