import axios, { AxiosInstance } from 'axios';

export interface Payment {
  id: string;
  amount: number;
  currency: string;
  status: 'pending' | 'completed' | 'failed' | 'refunded';
  paymentMethod: string;
  createdAt: string;
  description?: string;
}

export interface LedgerEntry {
  id: string;
  accountId: string;
  amount: number;
  currency: string;
  type: 'debit' | 'credit';
  description: string;
  timestamp: string;
  reference?: string;
}

export class FinanceClient {
  protected client: AxiosInstance;

  constructor(baseURL?: string) {
    const apiBaseURL =
      baseURL ||
      (typeof window !== 'undefined'
        ? process.env.NEXT_PUBLIC_FINANCE_SERVICE_URL || 'http://localhost:4005'
        : 'http://localhost:4005');

    this.client = axios.create({
      baseURL: apiBaseURL,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // Set up request interceptor for authentication
    this.client.interceptors.request.use(
      (config) => {
        const token = this.getAuthToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );
  }

  private getAuthToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('auth_token');
  }

  setAuthToken(token: string): void {
    if (typeof window !== 'undefined') {
      localStorage.setItem('auth_token', token);
    }
  }

  clearAuthToken(): void {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('auth_token');
    }
  }

  async createPayment(data: {
    amount: number;
    currency: string;
    paymentMethod: string;
    description?: string;
  }): Promise<Payment> {
    const response = await this.client.post<Payment>('/api/v1/payments', data);
    return response.data;
  }

  async getPayment(paymentId: string): Promise<Payment> {
    const response = await this.client.get<Payment>(`/api/v1/payments/${paymentId}`);
    return response.data;
  }

  async listPayments(filters?: {
    status?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{ payments: Payment[]; total: number }> {
    const response = await this.client.get<{ payments: Payment[]; total: number }>('/api/v1/payments', {
      params: filters,
    });
    return response.data;
  }

  async getLedgerEntries(filters?: {
    accountId?: string;
    type?: 'debit' | 'credit';
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{ entries: LedgerEntry[]; total: number }> {
    const response = await this.client.get<{ entries: LedgerEntry[]; total: number }>(
      '/api/v1/ledger',
      { params: filters }
    );
    return response.data;
  }
}
