import { requestJson } from './apiClient';

function normalizeItems(items) {
    if (Array.isArray(items)) return items;
    if (items && typeof items === 'object') return [items];
    return [];
}

export const UserService = {
    async listUsers({ page, limit, tenantID, username, status, sortField, sortOrder } = {}) {
        const query = { page, limit, tenantID, username, status };
        if (sortField && sortOrder) {
            if (sortOrder === 1) query.asc = sortField;
            if (sortOrder === -1) query.desc = sortField;
        }

        const data = await requestJson('/super/v1/users', { query });
        return {
            page: data?.page ?? page ?? 1,
            limit: data?.limit ?? limit ?? 10,
            total: data?.total ?? 0,
            items: normalizeItems(data?.items)
        };
    },
    async getUserStatuses() {
        try {
            const data = await requestJson('/super/v1/user/statuses');
            return Array.isArray(data) ? data : [];
        } catch (error) {
            if (error?.status === 404) {
                const data = await requestJson('/super/v1/users/statuses');
                return Array.isArray(data) ? data : [];
            }
            throw error;
        }
    },
    async updateUserStatus({ userID, status }) {
        try {
            return await requestJson(`/super/v1/user/${userID}/status`, { method: 'PATCH', body: { status } });
        } catch (error) {
            if (error?.status === 404) {
                return requestJson(`/super/v1/users/${userID}/status`, { method: 'PATCH', body: { status } });
            }
            throw error;
        }
    },
    async getUserStatistics() {
        try {
            const data = await requestJson('/super/v1/users/statistics');
            return Array.isArray(data) ? data : [];
        } catch (error) {
            if (error?.status === 404) {
                const data = await requestJson('/super/v1/users/statistic');
                return Array.isArray(data) ? data : [];
            }
            throw error;
        }
    }
};
