import { InMemoryEventBus } from "../hub/eventBus";
import { startYouTubeAdapter } from "../platform/youtube";

function delay(ms: number): Promise<void> {
    return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
}

function assert(condition: boolean, message: string): void {
    if (!condition) {
        throw new Error(message);
    }
}

async function main(): Promise<void> {
    const bus = new InMemoryEventBus();
    let tokenCalls = 0;
    let liveBroadcastCalls = 0;
    let streamCalls = 0;
    let liveChatCalls = 0;
    const logs: Array<{ message: string; fields: Record<string, unknown> }> = [];

    const fakeFetch: typeof fetch = async (input) => {
        const url =
            typeof input === "string" ? new URL(input) : input instanceof URL ? input : new URL(input.url);

        if (url.hostname === "oauth2.googleapis.com" && url.pathname === "/token") {
            tokenCalls += 1;
            return {
                ok: true,
                status: 200,
                statusText: "OK",
                json: async () => ({
                    access_token: `phase21-token-${tokenCalls}`,
                    expires_in: 300
                })
            } as Response;
        }

        if (url.pathname.endsWith("/liveBroadcasts")) {
            liveBroadcastCalls += 1;
            return {
                ok: true,
                status: 200,
                statusText: "OK",
                json: async () => ({
                    items: [{ snippet: { liveChatId: "phase21-live-chat-id" } }]
                })
            } as Response;
        }

        if (url.pathname.endsWith("/liveChat/messages")) {
            liveChatCalls += 1;
            return {
                ok: false,
                status: 401,
                statusText: "Unauthorized"
            } as Response;
        }

        throw new Error(`Unexpected URL in fakeFetch: ${url.toString()}`);
    };
    const fakeStreamList = async function* () {
        streamCalls += 1;
        const error = new Error("Unauthenticated") as Error & { code: number };
        error.code = 16;
        throw error;
    };

    const adapter = startYouTubeAdapter({
        eventBus: bus,
        apiKey: "fake-key",
        oauthClientId: "client-id",
        oauthClientSecret: "client-secret",
        oauthRefreshToken: "refresh-token",
        pollMs: 1,
        discoveryPollMs: 1000,
        errorLogCooldownMs: 1,
        fetchImpl: fakeFetch,
        streamListImpl: fakeStreamList,
        log: (message, fields = {}) => logs.push({ message, fields })
    });

    try {
        adapter.setAdminPresenceActive(true);
        adapter.armDiscovery();
        await delay(400);

        assert(tokenCalls >= 2, "Expected initial token plus refresh after stream auth failure.");
        assert(liveBroadcastCalls === 1, "Expected one discovery call.");
        assert(streamCalls === 1, "Expected one streamList attempt.");
        assert(
            liveChatCalls === 0,
            `Expected no fallback liveChat/messages polling after stream auth failure; got ${liveChatCalls} calls.`
        );
        assert(
            logs.some(
                (entry) =>
                    entry.message === "youtube_poll_error" &&
                    entry.fields.message ===
                        "YouTube streamList authorization failed; backing off before retry."
            ),
            "Expected auth backoff to be logged."
        );

        console.log(
            JSON.stringify(
                {
                    ok: true,
                    tokenCalls,
                    liveBroadcastCalls,
                    streamCalls,
                    liveChatCalls
                },
                null,
                2
            )
        );
    } finally {
        adapter.stop();
    }
}

main().catch((error: unknown) => {
    const message = error instanceof Error ? error.message : String(error);
    console.error(message);
    process.exit(1);
});
