import express from "express";
import cors from "cors";
import fs from "fs";
import path from "path";
import dotenv from "dotenv";
import { fileURLToPath } from "url";

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
app.use(cors());
app.use(express.json());

// === Thư mục cache ===
const CACHE_DIR = path.join(__dirname, "cache");
if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR);

// === Object lưu cache memory ===
const cache = {}; // { NAME: { info, dynamic, ip, lastUpdate } }

// Endpoint nhận POST từ VPS
app.post("/pushServerData", (req, res) => {
    const { name, info, dynamic } = req.body;

    if (!name || !info || !dynamic) {
        return res.status(400).json({ error: "Thiếu dữ liệu name, info hoặc dynamic" });
    }

    const senderIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'unknown';

    // Lưu vào memory cache
    cache[name] = {
        info,
        dynamic,
        ip: senderIp,
        lastUpdate: Date.now()
    };

    // Lưu ra file (backup)
    const filePath = path.join(CACHE_DIR, `${name}.json`);
    fs.writeFileSync(filePath, JSON.stringify(cache[name], null, 2));

    console.log(`✅ Lưu dữ liệu cho ${name} từ IP ${senderIp}`);
    return res.json({ success: true, message: `${name} đã được lưu`, ip: senderIp });
});

// Endpoint frontend GET dữ liệu theo NAME
app.get("/getServerData/:name", (req, res) => {
    const { name } = req.params;
    const data = cache[name];

    if (!data) return res.status(404).json({ error: "Server không tồn tại" });

    return res.json(data);
});

// Endpoint kiểm tra health push
app.get("/healthpush", (req, res) => {
    const serverCount = Object.keys(cache).length;
    const lastUpdates = Object.entries(cache).map(([name, value]) => ({
        name,
        lastUpdate: new Date(value.lastUpdate).toISOString(),
        ip: value.ip
    }));

    return res.json({
        status: "ok",
        serverCount,
        servers: lastUpdates
    });
});

// Start server
const PORT = process.env.PORT || 80;
app.listen(PORT, () => console.log(`🚀 Hosting backend running at http://localhost:${PORT}`));
