import { requestJson } from './apiClient';

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

export const CreatorService = {
    async listCreators({ page, limit, id, user_id, name, code, status, created_at_from, created_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,
            user_id,
            name,
            code,
            status,
            created_at_from: iso(created_at_from),
            created_at_to: iso(created_at_to)
        };
        if (sortField && sortOrder) {
            if (sortOrder === 1) query.asc = sortField;
            if (sortOrder === -1) query.desc = sortField;
        }

        const data = await requestJson('/super/v1/creators', { query });
        return {
            page: data?.page ?? page ?? 1,
            limit: data?.limit ?? limit ?? 10,
            total: data?.total ?? 0,
            items: normalizeItems(data?.items)
        };
    }
};
