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, id, tenant_id, username, status, role, created_at_from, created_at_to, verified_at_from, verified_at_to, sortField, sortOrder } = {}) {
        const iso = (d) => {
            if (!d) return undefined;
            const date = d instanceof Date ? d : new Date(d);
            if (Number.isNaN(date.getTime())) return undefined;
            return date.toISOString();
        };

        const query = {
            page,
            limit,
            id,
            tenant_id,
            username,
            status,
            role,
            created_at_from: iso(created_at_from),
            created_at_to: iso(created_at_to),
            verified_at_from: iso(verified_at_from),
            verified_at_to: iso(verified_at_to)
        };
        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 updateUserRoles({ userID, roles }) {
        if (!userID) throw new Error('userID is required');
        if (!Array.isArray(roles) || roles.length === 0) throw new Error('roles is required');
        return requestJson(`/super/v1/users/${userID}/roles`, { method: 'PATCH', body: { roles } });
    },
    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;
        }
    },
    async getUserDetail(userID) {
        if (!userID) throw new Error('userID is required');
        return requestJson(`/super/v1/users/${userID}`);
    },
    async listUserTenants(userID, { page, limit, tenant_id, code, name, role, status, created_at_from, created_at_to } = {}) {
        if (!userID) throw new Error('userID is required');

        const iso = (d) => {
            if (!d) return undefined;
            const date = d instanceof Date ? d : new Date(d);
            if (Number.isNaN(date.getTime())) return undefined;
            return date.toISOString();
        };

        const query = {
            page,
            limit,
            tenant_id,
            code,
            name,
            role,
            status,
            created_at_from: iso(created_at_from),
            created_at_to: iso(created_at_to)
        };

        const data = await requestJson(`/super/v1/users/${userID}/tenants`, { query });
        return {
            page: data?.page ?? page ?? 1,
            limit: data?.limit ?? limit ?? 10,
            total: data?.total ?? 0,
            items: normalizeItems(data?.items)
        };
    }
};
