import fs from "fs";
import configs from "../../system/config.js";
import { delay, getPathProfile, safeClosePage } from "../../system/utils.js";
import { ApiBid } from "../api-bid.js";

export class PicklesApiBid extends ApiBid {
  reloadInterval = null;
  constructor({ ...prev }) {
    super(prev);
  }

  action = async () => {
    try {
      const page = this.page_context;

      page.on("response", async (response) => {
        const request = response.request();
        if (request.redirectChain().length > 0) {
          if (response.url().includes(configs.WEB_CONFIGS.PICKLES.LOGIN_URL)) {
            await this.handleLogin();
          }
        }
      });

      await page.goto(this.url, { waitUntil: "networkidle2" });

      await page.bringToFront();

      // Set userAgent
      await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
      );
    } catch (error) {
      console.log("Error [action]: ", error.message);
    }
  };

  isLogin = async () => {
    if (!this.page_context) return false;

    const filePath = getPathProfile(this.origin_url);

    return (
      !(await this.page_context.$('[name="_58_login"]')) &&
      fs.existsSync(filePath)
    );
  };

  async handleLogin() {
    const page = this.page_context;

    global.IS_CLEANING = false;

    const filePath = getPathProfile(this.origin_url);

    await page.waitForNavigation({ waitUntil: "domcontentloaded" });

    // 🛠 Check if already logged in (login input should not be visible or profile exists)
    if (!(await page.$('[name="_58_login"]')) && fs.existsSync(filePath)) {
      console.log(`✅ [${this.id}] Already logged in, skipping login process.`);
      return;
    }

    if (fs.existsSync(filePath)) {
      console.log(`🗑 [${this.id}] Deleting existing file: ${filePath}`);
      fs.unlinkSync(filePath);
    }

    const children = this.children.filter((item) => item?.page_context);
    console.log(
      `🔍 [${this.id}] Found ${children.length} child pages to close.`
    );

    if (children.length > 0) {
      console.log(`🛑 [${this.id}] Closing child pages...`);
      await Promise.all(
        children.map((item) => {
          console.log(
            `➡ [${this.id}] Closing child page with context: ${item?.page_context}`
          );
          return safeClosePage(item);
        })
      );

      console.log(
        `➡ [${this.id}] Closing main page context: ${this.page_context}`
      );
      await safeClosePage(this);
    }

    console.log(`🔑 [${this.id}] Starting login process...`);

    try {
      // ⌨ Enter email
      console.log(`✍ [${this.id}] Entering email:`, this.username);
      await page.type('[name="_58_login"]', this.username, { delay: 100 });

      // ⌨ Enter password
      console.log(`✍ [${this.id}] Entering password...`);
      await page.type('[name="_58_password"]', this.password, { delay: 150 });

      // 🚀 Click the login button
      console.log(`🔘 [${this.id}] Clicking the "Login" button`);
      await page.click("#sign-in-btn", { delay: 92 });

      await page.waitForNavigation({
        timeout: 8000,
        waitUntil: "domcontentloaded",
      });

      if (this.page_context.url() == this.url) {
        // 📂 Save session context to avoid re-login
        await this.saveContext();
        console.log(`✅ [${this.id}] Login successful!`);
      } else {
        console.log(`❌ [${this.id}] Login Failure!`);
      }
    } catch (error) {
      console.error(
        `❌ [${this.id}] Error during login process:`,
        error.message
      );
    } finally {
      global.IS_CLEANING = true;
    }
  }

  listen_events = async () => {
    if (this.page_context) return;

    // await this.puppeteer_connect();
    // await this.action();

    const results = await this.handlePrevListen();

    if (!results) return;

    this.reloadInterval = setInterval(async () => {
      try {
        if (this.page_context && !this.page_context.isClosed()) {
          console.log(`🔄 [${this.id}] Reloading page...`);
          await this.page_context.reload({ waitUntil: "networkidle2" });
          console.log(`✅ [${this.id}] Page reloaded successfully.`);
        } else {
          console.log(
            `❌ [${this.id}] Page context is closed. Stopping reload.`
          );
          clearInterval(this.reloadInterval);
        }
      } catch (error) {
        console.error(`🚨 [${this.id}] Error reloading page:`, error.message);
      }
    }, 60000); // 1p reload
  };
}
