const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');

const requestedPages = [];
const responsesByPage = {
    1: {
        items: Array.from({ length: 20 }, (_, index) => ({
            resource_id: String(1000 - index),
            name: `Resource ${index + 1}`,
        })),
        page: 1,
        page_size: 20,
        total: 26,
    },
    2: {
        items: [
            { resource_id: '202', name: 'Rose' },
            { resource_id: '197', name: 'Stellar Aura' },
            { resource_id: '192', name: 'Bugatti' },
            { resource_id: '191', name: 'Cupid' },
            { resource_id: '175', name: 'SuperAdmin' },
            { resource_id: '165', name: 'Admin' },
        ],
        page: 2,
        page_size: 20,
        total: 26,
    },
};

function response(payload) {
    return {
        headers: { get: () => '' },
        ok: true,
        status: 200,
        statusText: 'OK',
        text: () =>
            Promise.resolve(
                JSON.stringify({ code: 'OK', message: 'ok', data: payload })
            ),
    };
}

async function main() {
    const storage = new Map();
    const window = {
        document: { documentElement: { setAttribute: () => {} } },
        fetch: (rawURL) => {
            const url = new URL(rawURL);
            assert.equal(
                url.pathname,
                '/api/v1/manager-center/resource-grants/resources'
            );
            assert.equal(url.searchParams.get('resource_type'), 'avatar_frame');
            assert.equal(url.searchParams.get('page_size'), '20');
            const page = Number(url.searchParams.get('page'));
            requestedPages.push(page);
            return Promise.resolve(response(responsesByPage[page]));
        },
        localStorage: {
            getItem: (key) => storage.get(key) || null,
            removeItem: (key) => storage.delete(key),
            setItem: (key, value) => storage.set(key, String(value)),
        },
        location: {
            hash: '',
            hostname: 'h5.global-interaction.com',
            href: 'https://h5.global-interaction.com/gonghui/manager-center/',
            origin: 'https://h5.global-interaction.com',
            pathname: '/gonghui/manager-center/',
            search: '',
        },
    };
    const context = vm.createContext({
        FormData,
        JSON,
        Math,
        Number,
        Object,
        Promise,
        String,
        URL,
        URLSearchParams,
        Uint32Array,
        window,
    });
    const apiSource = fs.readFileSync(
        path.join(__dirname, '..', 'common', 'api.js'),
        'utf8'
    );
    vm.runInContext(apiSource, context, { filename: 'common/api.js' });

    const result = await window.HyAppAPI.managerCenter.listAllResources(
        'avatar_frame',
        20
    );
    assert.deepEqual(requestedPages, [1, 2]);
    assert.equal(result.total, 26);
    assert.equal(result.items.length, 26);
    assert.ok(
        result.items.some(
            (item) => item.resource_id === '175' && item.name === 'SuperAdmin'
        )
    );
    assert.ok(
        result.items.some(
            (item) => item.resource_id === '165' && item.name === 'Admin'
        )
    );
}

main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});
