const express = require('express');
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3001;
const SESSION_FILE_PATH = path.join(__dirname, 'sessions', 'session.json');

app.use(bodyParser.json());

// Buat folder sesi kalau belum ada
if (!fs.existsSync(path.join(__dirname, 'sessions'))) {
  fs.mkdirSync(path.join(__dirname, 'sessions'));
}

app.post('/comment', async (req, res) => {
  const { ig_username, ig_password, post_url, comment } = req.body;
  console.log('📦 Payload diterima:', req.body);

  try {
    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });

    const page = await browser.newPage();
    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');
    await page.setViewport({ width: 1280, height: 800 });

    let loggedIn = false;
    if (fs.existsSync(SESSION_FILE_PATH)) {
      const cookies = JSON.parse(fs.readFileSync(SESSION_FILE_PATH));
      await page.setCookie(...cookies);
      console.log('✅ Sesi login dimuat');
    }

    await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    loggedIn = await page.evaluate(() => {
      return !!document.querySelector('svg[aria-label="Beranda"], svg[aria-label="Home"]');
    });

    if (!loggedIn) {
      console.log('🔐 Login ulang...');
      await page.goto('https://www.instagram.com/accounts/login/', { waitUntil: 'networkidle2' });

      await page.waitForSelector('input[name="username"]', { timeout: 15000 });
      await page.type('input[name="username"]', ig_username, { delay: 100 });
      await page.type('input[name="password"]', ig_password, { delay: 100 });
      await page.keyboard.press('Enter');

      await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 15000 }).catch(() => {});
      await new Promise(resolve => setTimeout(resolve, 4000));

      if (page.url().includes('/onetap')) {
        console.log('🔁 Redirect dari Instagram One Tap, alihkan ke beranda...');
        await page.goto('https://www.instagram.com/', { waitUntil: 'networkidle2' });
        await new Promise(resolve => setTimeout(resolve, 3000));
      }

      const loginFailed = await page.evaluate(() => {
        return (
          document.body.innerText.includes('kata sandi Anda salah') ||
          document.body.innerText.includes('Your password was incorrect') ||
          document.body.innerText.includes('Try again')
        );
      });

      if (loginFailed) {
        throw new Error('Login gagal: username atau password salah');
      }

      const cookies = await page.cookies();
      fs.writeFileSync(SESSION_FILE_PATH, JSON.stringify(cookies, null, 2));
      console.log('💾 Sesi login disimpan');
    }

    // Kunjungi postingan
    await page.goto(post_url, { waitUntil: 'networkidle2' });
    await new Promise(resolve => setTimeout(resolve, 3000));

    await page.evaluate(() => window.scrollBy(0, window.innerHeight));
    await new Promise(resolve => setTimeout(resolve, 2000));

    await page.screenshot({ path: 'debug_screenshot.png', fullPage: true });

    const commentBoxSelector = 'form textarea';
    await page.waitForSelector(commentBoxSelector, { timeout: 15000 });

    await page.click(commentBoxSelector);
    await page.type(commentBoxSelector, comment, { delay: 50 });

    await new Promise(resolve => setTimeout(resolve, 2000));
    await page.keyboard.press('Enter');

    console.log('✅ Komentar berhasil dikirim');
    res.json({ success: true, message: 'Komentar berhasil dikirim!' });
    await browser.close();
  } catch (error) {
    console.error('❌ ERROR:', error);
    res.status(500).json({ success: false, message: 'Gagal kirim komentar', error: error.message });
  }
});

app.listen(PORT, () => {
  console.log(`🚀 Bot berjalan di http://localhost:${PORT}`);
});
