import { requestJson } from './apiClient';

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

export const TenantService = {
    async listTenants({ page, limit, name, code, status, sortField, sortOrder } = {}) {
        const query = { page, limit, name, code, status };
        if (sortField && sortOrder) {
            if (sortOrder === 1) query.asc = sortField;
            if (sortOrder === -1) query.desc = sortField;
        }

        const data = await requestJson('/super/v1/tenants', { query });
        return {
            page: data?.page ?? page ?? 1,
            limit: data?.limit ?? limit ?? 10,
            total: data?.total ?? 0,
            items: normalizeItems(data?.items)
        };
    },
    async renewTenantExpire({ tenantID, duration }) {
        return requestJson(`/super/v1/tenants/${tenantID}`, {
            method: 'PATCH',
            body: { duration }
        });
    },
    async getTenantStatuses() {
        const data = await requestJson('/super/v1/tenants/statuses');
        return Array.isArray(data) ? data : [];
    },
    async updateTenantStatus({ tenantID, status }) {
        return requestJson(`/super/v1/tenants/${tenantID}/status`, {
            method: 'PATCH',
            body: { status }
        });
    }
};
