import { api } from './api';
import { CreateTreasuryPlanDTO, TreasuryPlanDTO } from '@/types/treasury';

export const treasuryPlanService = {
    // Criar novo plano
    create: async (data: CreateTreasuryPlanDTO): Promise<TreasuryPlanDTO> => {
        const response = await api.post<TreasuryPlanDTO>('/treasury/plans', data);
        return response;
    },

    // Aprovar plano
    approve: async (id: string, approverId: string): Promise<TreasuryPlanDTO> => {
        const response = await api.put<TreasuryPlanDTO>(`/treasury/plans/${id}/approve?approverId=${approverId}`);
        return response;
    },

    // Buscar plano por ID
    getById: async (id: string): Promise<TreasuryPlanDTO> => {
        const response = await api.get<TreasuryPlanDTO>(`/treasury/plans/${id}`);
        return response;
    },

    // Listar planos por status
    findByStatus: async (status: string): Promise<TreasuryPlanDTO[]> => {
        const response = await api.get<TreasuryPlanDTO[]>(`/treasury/plans/status/${status}`);
        return response;
    },

    // Buscar plano ativo para uma data
    findActivePlan: async (date: string): Promise<TreasuryPlanDTO | null> => {
        try {
            const response = await api.get<TreasuryPlanDTO>(`/treasury/plans/active?date=${date}`);
            return response;
        } catch (error: any) {
            // Se não houver plano ativo, retorna 404 - isso é esperado
            if (error.response?.status === 404) {
                return null;
            }
            throw error;
        }
    },
};
