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

const root = path.join(__dirname, '..');

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

function harness(search = '') {
    const requests = [];
    const location = {
        hash: '',
        hostname: 'h5.global-interaction.com',
        href: `https://h5.global-interaction.com/guild/fami/host-center/${search}`,
        origin: 'https://h5.global-interaction.com',
        pathname: '/guild/fami/host-center/',
        search,
    };
    const storage = new Map();
    const window = {
        atob: (value) => Buffer.from(value, 'base64').toString('binary'),
        document: {
            currentScript: null,
            documentElement: { setAttribute: () => {} },
        },
        dispatchEvent: () => {},
        fetch: (rawURL, options = {}) => {
            const url = new URL(rawURL);
            requests.push({ url, options });
            if (url.pathname === '/api/v1/users/me') {
                return Promise.resolve(
                    apiResponse({
                        user_id: '42',
                        display_user_id: '100042',
                        username: 'Fami Host',
                        contact_info: '+90 555 0100',
                    })
                );
            }
            if (url.pathname === '/api/v1/host-center/agency') {
                return Promise.resolve(
                    apiResponse({
                        agency: {
                            agency_id: '9',
                            short_id: '90009',
                            name: 'Fami Agency',
                            joined_at_ms: 1_750_000_000_000,
                        },
                    })
                );
            }
            if (url.pathname === '/api/v1/wallet/me/balances') {
                return Promise.resolve(
                    apiResponse({
                        balances: [
                            { asset_type: 'POINT', available_amount: 8800 },
                        ],
                    })
                );
            }
            if (url.pathname === '/api/v1/host-center/stats') {
                return Promise.resolve(
                    apiResponse({
                        metrics: {
                            diamond_earnings: 700,
                            diamond_exchanged: 200,
                            gift_senders: 3,
                            online_duration_ms: 7200000,
                            valid_mic_duration_ms: 3600000,
                            valid_mic_days: 1,
                            private_message_senders: 4,
                            new_followers: 5,
                        },
                    })
                );
            }
            return Promise.resolve(apiResponse({}));
        },
        localStorage: {
            getItem: (key) => storage.get(key) || null,
            removeItem: (key) => storage.delete(key),
            setItem: (key, value) => storage.set(key, String(value)),
        },
        location,
    };
    window.window = window;
    const context = vm.createContext({
        Buffer,
        CustomEvent: function CustomEvent() {},
        Date,
        Error,
        FormData,
        JSON,
        Math,
        Number,
        Object,
        Promise,
        String,
        URL,
        URLSearchParams,
        console,
        document: window.document,
        window,
    });
    return { context, requests, window };
}

function run(context, file) {
    vm.runInContext(fs.readFileSync(path.join(root, file), 'utf8'), context, {
        filename: file,
    });
}

async function main() {
    const browser = harness('?token=test-token&env=test');
    run(browser.context, 'guild/packages/core/product-context.js');
    run(browser.context, 'guild/products/fami/product.js');
    run(browser.context, 'common/api.js');
    run(browser.context, 'guild/packages/core/date-range.js');
    run(browser.context, 'guild/packages/host-center/host-center.js');

    const range = browser.window.HyGuild.dateRange.create('last_7_days', {
        now: new Date(2026, 6, 12),
    });
    const data = await browser.window.HyGuild.hostCenter.load(range);
    assert.equal(data.profile.displayUserId, '100042');
    assert.equal(data.agency.joinedAtMS, 1_750_000_000_000);
    assert.equal(data.pointBalance, 8800);
    assert.equal(data.stats.metrics.private_message_senders, 4);
    assert.deepEqual(Object.keys(data.errors), []);

    const statsRequest = browser.requests.find(
        ({ url }) => url.pathname === '/api/v1/host-center/stats'
    );
    assert.ok(statsRequest, 'host stats endpoint must be requested');
    assert.equal(statsRequest.url.searchParams.get('start_date'), '2026-07-06');
    assert.equal(statsRequest.url.searchParams.get('end_date'), '2026-07-12');
    browser.requests.forEach(({ options }) => {
        assert.equal(options.headers['X-App-Code'], 'fami');
    });

    const mockBrowser = harness('?mock=1');
    run(mockBrowser.context, 'guild/packages/core/product-context.js');
    run(mockBrowser.context, 'guild/products/fami/product.js');
    run(mockBrowser.context, 'guild/packages/core/date-range.js');
    run(mockBrowser.context, 'guild/packages/host-center/host-center.js');
    const mock = await mockBrowser.window.HyGuild.hostCenter.load(
        mockBrowser.window.HyGuild.dateRange.create('today', {
            now: new Date(2026, 6, 12),
        })
    );
    assert.equal(mock.pointBalance, 5152051511212);
    assert.equal(mockBrowser.requests.length, 0);

    console.log('Fami host center tests passed');
}

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