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/bd-center/${search}`,
        origin: 'https://h5.global-interaction.com',
        pathname: '/guild/fami/bd-center/',
        search,
    };
    const storage = new Map();
    const window = {
        atob: (value) => Buffer.from(value, 'base64').toString('binary'),
        crypto: { randomUUID: () => 'fixed-uuid' },
        document: {
            currentScript: null,
            documentElement: { setAttribute: () => {} },
        },
        dispatchEvent: () => {},
        fetch: (rawURL, options = {}) => {
            const url = new URL(rawURL);
            requests.push({ url, options });
            if (url.pathname === '/api/v1/bd-center/overview')
                return Promise.resolve(
                    apiResponse({
                        profile: {
                            user_id: '7',
                            display_user_id: '100007',
                            username: 'Fami BD',
                            contact_info: '+90 555',
                        },
                        bd_profile: { user_id: '7' },
                    })
                );
            if (url.pathname === '/api/v1/bd-center/stats')
                return Promise.resolve(
                    apiResponse({
                        items: [
                            {
                                agency: {
                                    agency_id: '9',
                                    short_id: '90009',
                                    name: 'Fami Stars',
                                },
                                owner: {
                                    display_user_id: '100042',
                                    username: 'Owner',
                                },
                                country: 'Türkiye',
                                total_hosts: 4,
                                gifted_host_count: 3,
                                diamond_earnings: 7700,
                                joined_at_ms: 1750000000000,
                            },
                        ],
                    })
                );
            if (url.pathname === '/api/v1/users/by-display-user-id/100099')
                return Promise.resolve(apiResponse({ user_id: '99' }));
            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;
    return {
        context: vm.createContext({
            Buffer,
            CustomEvent: function CustomEvent() {},
            Date,
            Error,
            FormData,
            JSON,
            Math,
            Number,
            Object,
            Promise,
            String,
            URL,
            URLSearchParams,
            console,
            document: window.document,
            window,
        }),
        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/bd-center/bd-center.js');
    const range = browser.window.HyGuild.dateRange.create('last_7_days', {
        now: new Date(2026, 6, 12),
    });
    const data = await browser.window.HyGuild.bdCenter.load(range);
    assert.equal(data.profile.displayUserId, '100007');
    assert.equal(data.stats.agencies[0].diamondEarnings, 7700);
    assert.equal(data.stats.agencies[0].country, 'Türkiye');
    await browser.window.HyGuild.bdCenter.inviteAgency('100099', 'New Stars');
    const invite = browser.requests.find(
        ({ url }) => url.pathname === '/api/v1/bd/invitations/agency'
    );
    assert.deepEqual(JSON.parse(invite.options.body), {
        command_id: 'fami-bd-invite-agency:fixed-uuid',
        target_user_id: '99',
        agency_name: 'New Stars',
    });
    const stats = browser.requests.find(
        ({ url }) => url.pathname === '/api/v1/bd-center/stats'
    );
    assert.equal(stats.url.searchParams.get('start_date'), '2026-07-06');
    assert.equal(stats.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/bd-center/bd-center.js');
    const mock = await mockBrowser.window.HyGuild.bdCenter.load(
        mockBrowser.window.HyGuild.dateRange.create('today', {
            now: new Date(2026, 6, 12),
        })
    );
    assert.equal(mock.stats.agencies.length, 1);
    assert.equal(mockBrowser.requests.length, 0);
    console.log('Fami BD center tests passed');
}
main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});
