import { chromium } from "playwright";
import uniqueRandomArray from "unique-random-array";
import userAgents from "top-user-agents";

export async function login(email, password) {
    const browser = await chromium.launch({
        headless: true,
        devtools: false,
    });

    const page = await browser.newPage({
        userAgent: uniqueRandomArray(userAgents)(),
        viewport: {
            width: parseInt(Math.random() * 100 + 1250),
            height: parseInt(Math.random() * 100 + 750),
        },
        locale: "en-CA",
        timezoneId: "America/Toronto",
    });

    let points = null;

    await page.route(/points$/, async (route, request) => {
        const response = await route.fetch();
        points = await response.text();
        await route.continue();
    });
    await page.route(/(\.png$)|(\.jpg$)/i, (route) => route.abort());

    await page.goto("https://www.pcoptimum.ca/");

    const link = await page.$('a > span:has-text("sign in")');
    link.click();

    await page.waitForURL("https://accounts.pcid.ca/login");

    await page.fill('input[id="email"]', email);
    await page.fill('input[id="password"]', password);

    try {
        await new Promise(async (resolve, reject) => {
            await page.route(/\/login$/, async (route, request) => {
                console.log(
                    `${request.method()}  ${request.resourceType()} ${request.url()}`
                );
                if (request.method() === "POST") {
                    const response = await route.fetch();
                    const status = response.status();
                    console.log(status);
                    if (status === 200) {
                        await route.continue();
                        resolve();
                    } else if (status === 401) {
                        reject(new Error("Invalid email or password"));
                    } else if (status === 429) {
                        reject(
                            new Error(
                                "Oops, something went wrong. Please try again later."
                            )
                        );
                    } else {
                        reject(
                            new Error("Unknown error. Please try again later.")
                        );
                    }
                } else {
                    await route.continue();
                }
            });

            await page.click('button:has-text("Sign in")');
        });
    } catch (error) {
        await browser.close();
        throw error;
    }

    try {
        await page.waitForURL("https://www.pcoptimum.ca/dashboard");
        await page.waitForTimeout(5000);
    } catch (error) {
        console.error(error.stack);
    }

    await browser.close();

    return points;
}
