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

export interface ProfitLossReport {
  period: {
    start_date: string;
    end_date: string;
    fiscal_period_id?: number;
  };
  revenue: {
    total_revenue: number;
    revenue_by_account: Record<string, number>;
  };
  costs: {
    total_cogs: number;
    gross_profit: number;
  };
  expenses: {
    total_operating_expenses: number;
    expenses_by_account: Record<string, number>;
  };
  profit: {
    net_profit: number;
    profit_margin: number;
  };
}

export interface BalanceSheetReport {
  as_of_date: string;
  fiscal_period_id?: number;
  assets: {
    breakdown: Record<string, number>;
    total_assets: number;
  };
  liabilities: {
    breakdown: Record<string, number>;
    total_liabilities: number;
  };
  equity: {
    breakdown: Record<string, number>;
    total_equity: number;
  };
  balance: {
    total_liabilities_and_equity: number;
    is_balanced: boolean;
  };
}

export interface TaxReport {
  period: {
    start_date: string;
    end_date: string;
  };
  total_tax_collected: number;
  total_taxable_amount: number;
  transactions: Array<{
    invoice_number: string;
    customer_name: string;
    taxable_amount: number;
    tax_amount: number;
    tax_rate: number;
    transaction_date: string;
  }>;
}

class FinancialReportService {
  async getProfitLoss(params?: {
    start_date?: string;
    end_date?: string;
    fiscal_period_id?: number;
  }): Promise<{ status: string; data: ProfitLossReport }> {
    const response = await apiClient.get('/financial/profit-loss', { params });
    return response.data;
  }

  async getBalanceSheet(params?: {
    as_of_date?: string;
    fiscal_period_id?: number;
  }): Promise<{ status: string; data: BalanceSheetReport }> {
    const response = await apiClient.get('/financial/balance-sheet', { params });
    return response.data;
  }

  async getTaxReport(params?: {
    start_date?: string;
    end_date?: string;
    format?: 'json' | 'csv';
  }): Promise<{ status: string; data: TaxReport } | Blob> {
    const response = await apiClient.get('/financial/tax-report', { 
      params,
      responseType: params?.format === 'csv' ? 'blob' : 'json'
    });
    return response.data;
  }
}

const financialReportService = new FinancialReportService();
export default financialReportService;

