/**
 * Service for accessing financial audit trail
 */
import apiClient from '../../../shared/services/apiClient';

export interface FinancialAuditRecord {
  id: number;
  action_type: string;
  action_description: string;
  payment_id?: number;
  invoice_id?: number;
  booking_id?: number;
  amount?: number;
  previous_amount?: number;
  currency: string;
  performed_by: number;
  performed_by_email?: string;
  metadata?: Record<string, unknown>;
  notes?: string;
  created_at: string;
}

export interface FinancialAuditFilters {
  payment_id?: number;
  invoice_id?: number;
  booking_id?: number;
  action_type?: string;
  user_id?: number;
  start_date?: string;
  end_date?: string;
  page?: number;
  limit?: number;
}

const financialAuditService = {
  /**
   * Get financial audit trail with filters
   */
  async getAuditTrail(filters: FinancialAuditFilters = {}) {
    const params = new URLSearchParams();
    if (filters.payment_id) params.append('payment_id', filters.payment_id.toString());
    if (filters.invoice_id) params.append('invoice_id', filters.invoice_id.toString());
    if (filters.booking_id) params.append('booking_id', filters.booking_id.toString());
    if (filters.action_type) params.append('action_type', filters.action_type);
    if (filters.user_id) params.append('user_id', filters.user_id.toString());
    if (filters.start_date) params.append('start_date', filters.start_date);
    if (filters.end_date) params.append('end_date', filters.end_date);
    if (filters.page) params.append('page', filters.page.toString());
    if (filters.limit) params.append('limit', filters.limit.toString());

    const response = await apiClient.get(`/financial/audit-trail?${params.toString()}`);
    return response.data;
  },

  /**
   * Get a specific audit record
   */
  async getAuditRecord(recordId: number) {
    const response = await apiClient.get(`/financial/audit-trail/${recordId}`);
    return response.data;
  },

  /**
   * Export audit trail to CSV or JSON
   */
  async exportAuditTrail(filters: FinancialAuditFilters = {}, format: 'csv' | 'json' = 'csv'): Promise<Blob> {
    const params = new URLSearchParams();
    if (filters.payment_id) params.append('payment_id', filters.payment_id.toString());
    if (filters.invoice_id) params.append('invoice_id', filters.invoice_id.toString());
    if (filters.booking_id) params.append('booking_id', filters.booking_id.toString());
    if (filters.action_type) params.append('action_type', filters.action_type);
    if (filters.user_id) params.append('user_id', filters.user_id.toString());
    if (filters.start_date) params.append('start_date', filters.start_date);
    if (filters.end_date) params.append('end_date', filters.end_date);
    params.append('format', format);

    const response = await apiClient.get(`/financial/audit-trail/export?${params.toString()}`, {
      responseType: 'blob'
    });
    return response.data;
  },
};

export default financialAuditService;

