const mysql = require("mysql2/promise");
const https = require("https");

async function fetchJSON(url){
  return new Promise((resolve, reject) => {
    https.get(url, res => {
      let data = "";
      res.on("data", d => data += d);
      res.on("end", () => {
        try {
          resolve(JSON.parse(data));
        } catch (e) {
          reject("JSON parse hatası");
        }
      });
    }).on("error", reject);
  });
}

(async () => {
  try {

    // 🔵 DB BAĞLANTI
    const db = await mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "12345678",
      database: "item_takip"
    });

    // 🔵 SONTEKLİF JSON (SON SATILANLAR)
    const apiUrl =
      "https://www.sonteklif.com/api/oyuncu-pazari/son-satilanlar?oyun=rise-online&limit=10";

    const json = await fetchJSON(apiUrl);

    if(!json || !Array.isArray(json.data)){
      throw "API veri dönmedi";
    }

    let inserted = 0;
    let total = json.data.length;

    for(const item of json.data){

      const ilanId = String(item.id);
      const baslik = item.title || "";
      const fiyat = item.price || "";
      const ilanUrl = "https://www.sonteklif.com" + item.url;

      // 🔴 VAR MI KONTROLÜ
      const [rows] = await db.execute(
        "SELECT id FROM sonteklif_son_satilanlar WHERE ilan_id=? LIMIT 1",
        [ilanId]
      );

      if(rows.length > 0){
        continue;
      }

      // 🟢 EKLE
      await db.execute(
        `INSERT INTO sonteklif_son_satilanlar
        (ilan_id, baslik, fiyat, ilan_url)
        VALUES (?,?,?,?)`,
        [ilanId, baslik, fiyat, ilanUrl]
      );

      inserted++;
    }

    console.log(JSON.stringify({
      ok: true,
      inserted,
      totalFound: total
    }));

    await db.end();

  } catch (err) {
    console.log(JSON.stringify({
      ok: false,
      error: String(err)
    }));
  }
})();
