import API from '../api/API';
import { toast } from 'sonner';

export const adminService = {
    extractErrorMessage(error: any, fallback: string) {
        return (
            error?.response?.data?.message ||
            error?.data?.message ||
            error?.message ||
            fallback
        );
    },

    async getAllUsers(params?: any) {
        try {
            const response = await API.getUsers(params) as any;
            return response.data;
        } catch (error: any) {
            console.error('Error fetching users:', error);
            toast.error(error.response?.data?.message || 'Failed to fetch users');
            return { success: false, data: [] };
        }
    },

    async createUser(userData: any) {
        try {
            const response = await API.createUser(userData) as any;
            if (response.ok && response.data?.success) {
                // Toast handled in component
            }
            return response.data;
        } catch (error: any) {
            console.error('Error creating user:', error);
            const message = this.extractErrorMessage(error, 'Failed to create user');
            toast.error(message);
            return { success: false, message };
        }
    },

    async updateUser(id: string, userData: any) {
        try {
            const response = await API.updateUser(id, userData) as any;
            if (response.ok && response.data?.success) {
                toast.success(response.data.message || 'User updated successfully');
            }
            return response.data;
        } catch (error: any) {
            console.error('Error updating user:', error);
            toast.error(error.response?.data?.message || 'Failed to update user');
            return { success: false };
        }
    },

    async updateUserStatus(id: string, status: string, isActive: boolean) {
        try {
            const response = await API.updateUserStatus(id, { status, isActive }) as any;
            if (response.ok && response.data?.success) {
                toast.success(response.data.message || 'User status updated');
            }
            return response.data;
        } catch (error: any) {
            console.error('Error updating status:', error);
            toast.error(error.response?.data?.message || 'Failed to update status');
            return { success: false };
        }
    }
};
