import { create } from 'zustand';
import { api } from './auth';

interface FinanceStore {
  payrollRuns: any[];
  payslips: any[];
  expenses: any[];
  
  fetchPayrollRuns: () => Promise<void>;
  fetchPayslips: () => Promise<void>;
  fetchExpenses: () => Promise<void>;
  
  createPayrollRun: (data: any) => Promise<void>;
  generatePayslips: (payrollRunId: number) => Promise<void>;
  createExpense: (data: any) => Promise<void>;
}

export const useFinanceStore = create<FinanceStore>((set, get) => ({
  payrollRuns: [],
  payslips: [],
  expenses: [],

  fetchPayrollRuns: async () => {
    const response = await api.get('/api/finance/payroll/runs');
    set({ payrollRuns: response.data });
  },

  fetchPayslips: async () => {
    const response = await api.get('/api/finance/payroll/payslips');
    set({ payslips: response.data });
  },

  fetchExpenses: async () => {
    const response = await api.get('/api/expenses');
    set({ expenses: response.data });
  },

  createPayrollRun: async (data: any) => {
    await api.post('/api/finance/payroll/runs', data);
    get().fetchPayrollRuns();
  },

  generatePayslips: async (payrollRunId: number) => {
    await api.post('/api/finance/payroll/payslips/generate', { payroll_run_id: payrollRunId });
    get().fetchPayslips();
  },

  createExpense: async (data: any) => {
    await api.post('/api/expenses', data);
    get().fetchExpenses();
  },
}));
