import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { InvoiceState, InvoiceFormData, Invoice } from '../../types/invoice';
import { api } from '../../services/api';

const initialState: InvoiceState = {
  invoices: [],
  loading: false,
  error: null
};

export const createInvoice = createAsyncThunk(
  'invoice/create',
  async (data: InvoiceFormData) => {
    const response = await api.post<Invoice>('/invoices', data);
    return response.data;
  }
);

const invoiceSlice = createSlice({
  name: 'invoice',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(createInvoice.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createInvoice.fulfilled, (state, action) => {
        state.loading = false;
        state.invoices.push(action.payload);
      })
      .addCase(createInvoice.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to create invoice';
      });
  }
});

export default invoiceSlice.reducer;