const express = require("express");
const router = express.Router();
const https = require("https");
const http = require("http");
const crypto = require("crypto");

const API_BASE_URL = "https://za-tool-kh.com/api/";
const ADMIN_SECRET = "Admin1688";

const TOPUP_AMOUNTS = [
  { pay: 5,  credit: 6  },
  { pay: 10, credit: 12 },
  { pay: 15, credit: 18 },
  { pay: 20, credit: 24 },
  { pay: 30, credit: 36 },
  { pay: 50, credit: 60 },
];

const pendingTxns = new Map();

// Simple HTTP GET helper
function httpGet(url, timeoutMs = 8000) {
  return new Promise((resolve, reject) => {
    const mod = url.startsWith("https") ? https : http;
    const req = mod.get(url, { timeout: timeoutMs }, (res) => {
      let data = "";
      res.on("data", c => data += c);
      res.on("end", () => {
        try { resolve(JSON.parse(data)); }
        catch { resolve(data); }
      });
    });
    req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
    req.on("error", reject);
  });
}

// Simple HTTP POST helper
function httpPost(url, body, timeoutMs = 10000) {
  return new Promise((resolve, reject) => {
    const payload = JSON.stringify(body);
    const parsed = new URL(url);
    const mod = parsed.protocol === "https:" ? https : http;
    const options = {
      hostname: parsed.hostname,
      port: parsed.port || (parsed.protocol === "https:" ? 443 : 80),
      path: parsed.pathname + parsed.search,
      method: "POST",
      headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) },
      timeout: timeoutMs,
    };
    const req = mod.request(options, (res) => {
      let data = "";
      res.on("data", c => data += c);
      res.on("end", () => {
        try { resolve(JSON.parse(data)); }
        catch { resolve(data); }
      });
    });
    req.on("timeout", () => { req.destroy(); reject(new Error("timeout")); });
    req.on("error", reject);
    req.write(payload);
    req.end();
  });
}

// GET /zapi/apitopup/amounts
router.get("/amounts", (req, res) => {
  res.json(TOPUP_AMOUNTS);
});

// POST /zapi/apitopup/check-key
router.post("/check-key", async (req, res) => {
  const { api_key } = req.body;
  if (!api_key || typeof api_key !== "string" || api_key.trim().length < 3) {
    return res.status(400).json({ ok: false, message: "API Key មិនត្រឹមត្រូវ" });
  }
  try {
    const url = `${API_BASE_URL}?action=balance&api_key=${encodeURIComponent(api_key.trim())}`;
    const data = await httpGet(url);
    if (data && (data.status === "success" && data.balance !== undefined)) {
      return res.json({ ok: true, balance: data.balance });
    }
    return res.status(404).json({ ok: false, message: "API Key រកមិនឃើញ" });
  } catch (e) {
    return res.status(502).json({ ok: false, message: "API Key មិនត្រឹមត្រូវ ឬ server មានបញ្ហា" });
  }
});

// POST /zapi/apitopup/generate-qr
router.post("/generate-qr", async (req, res) => {
  const { type, api_key, amount_pay } = req.body;
  const validAmounts = TOPUP_AMOUNTS.map(a => a.pay);
  if (!validAmounts.includes(Number(amount_pay))) {
    return res.status(400).json({ ok: false, message: "ចំនួនទឹកប្រាក់មិនត្រឹមត្រូវ" });
  }
  if (type === "topup" && !api_key) {
    return res.status(400).json({ ok: false, message: "តម្រូវឱ្យបញ្ចូល API Key" });
  }
  const pkg = TOPUP_AMOUNTS.find(a => a.pay === Number(amount_pay));
  const amount_credit = pkg.credit;
  const md5 = crypto.createHash("md5").update(`${type}-${api_key||"new"}-${amount_pay}-${Date.now()}`).digest("hex");

  try {
    const port = process.env.PORT || 3000;
    const qrData = await httpPost(
      `http://localhost:${port}/zapi/payment/khqr`,
      { amount: Number(amount_pay), tag: `API-${md5.slice(0,8)}` }
    );
    const txn = { md5, type, api_key: api_key || null, amount_pay: Number(amount_pay), amount_credit, status: "PENDING", created_at: Date.now() };
    pendingTxns.set(md5, txn);
    setTimeout(() => pendingTxns.delete(md5), 20 * 60 * 1000);
    return res.json({ ok: true, md5, amount_pay, amount_credit, qr: qrData });
  } catch (e) {
    return res.status(500).json({ ok: false, message: "បង្កើត QR មានបញ្ហា: " + (e.message || "") });
  }
});

// POST /zapi/apitopup/check-payment
router.post("/check-payment", async (req, res) => {
  const { md5 } = req.body;
  if (!md5) return res.status(400).json({ ok: false, message: "md5 required" });
  const txn = pendingTxns.get(md5);
  if (!txn) return res.status(404).json({ ok: false, message: "Transaction រកមិនឃើញ ឬផុតកំណត់" });
  if (txn.status === "PAID") return res.json({ ok: true, status: "PAID", type: txn.type, new_key: txn.new_key || null, api_key: txn.api_key || null, amount_credit: txn.amount_credit });

  try {
    const checkData = await httpGet(`https://mmotool.dev/check_payment.php?md5=${encodeURIComponent(md5)}`);
    const status = checkData?.status || "UNPAID";
    if (status === "PAID") {
      txn.status = "PAID";
      if (txn.type === "topup") {
        await httpGet(`${API_BASE_URL}?action=admin_topup_user&admin_key=${ADMIN_SECRET}&user_key=${encodeURIComponent(txn.api_key)}&amount=${txn.amount_credit}`);
        return res.json({ ok: true, status: "PAID", type: "topup", api_key: txn.api_key, amount_credit: txn.amount_credit });
      } else {
        const newKey = "ZA-" + crypto.randomBytes(10).toString("hex").toUpperCase();
        const createData = await httpGet(`${API_BASE_URL}?action=admin_add_user&admin_key=${ADMIN_SECRET}&new_user_key=${encodeURIComponent(newKey)}&amount=${txn.amount_credit}`);
        if (createData?.status === "success") {
          txn.new_key = newKey;
          return res.json({ ok: true, status: "PAID", type: "buy_new", new_key: newKey, amount_credit: txn.amount_credit });
        }
        return res.json({ ok: false, status: "PAID_BUT_ERROR", message: "បង្កើត Key មានបញ្ហា — ទំនាក់ @za_farm_support_3337" });
      }
    }
    return res.json({ ok: true, status: "UNPAID" });
  } catch (e) {
    return res.status(500).json({ ok: false, message: "ឆែកការទូទាត់មានបញ្ហា" });
  }
});

module.exports = router;
