"use strict";
// @ts-nocheck
const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const { URL } = require("node:url");
const rootDir = path.resolve(__dirname, "..");
const dataDir = path.join(rootDir, "data");
const dataFile = path.join(dataDir, "tickets.json");
function ensureData() {
    if (!fs.existsSync(dataDir))
        fs.mkdirSync(dataDir, { recursive: true });
    if (!fs.existsSync(dataFile)) {
        const seed = [
            makeTicket("Printer kantor cabang offline", "Hardware", "high", "Doni", "Cek kabel USB dan restart spooler"),
            makeTicket("User tidak bisa login Wi-Fi", "Network", "medium", "Rina", "Reset credential dan uji AP terdekat"),
            makeTicket("Permintaan instalasi browser", "Software", "low", "Lina", "Siapkan paket install standar")
        ];
        fs.writeFileSync(dataFile, JSON.stringify(seed, null, 2), "utf-8");
    }
}
function loadTickets() {
    ensureData();
    return JSON.parse(fs.readFileSync(dataFile, "utf-8"));
}
function saveTickets(tickets) {
    fs.writeFileSync(dataFile, JSON.stringify(tickets, null, 2), "utf-8");
}
function makeId() {
    return `TCK-${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
}
function now() {
    return new Date().toISOString();
}
function makeTicket(title, category, priority, owner, notes) {
    const stamp = now();
    return {
        id: makeId(),
        title,
        category,
        priority,
        owner,
        status: "open",
        notes,
        createdAt: stamp,
        updatedAt: stamp,
    };
}
function metrics(tickets) {
    return {
        total: tickets.length,
        open: tickets.filter((t) => t.status === "open").length,
        inProgress: tickets.filter((t) => t.status === "in_progress").length,
        resolved: tickets.filter((t) => t.status === "resolved").length,
        highPriority: tickets.filter((t) => t.priority === "high").length,
    };
}
function writeJson(res, code, payload) {
    res.writeHead(code, { "Content-Type": "application/json; charset=utf-8" });
    res.end(JSON.stringify(payload, null, 2));
}
function readBody(req) {
    return new Promise((resolve) => {
        let raw = "";
        req.on("data", (chunk) => raw += chunk);
        req.on("end", () => {
            try {
                resolve(raw ? JSON.parse(raw) : {});
            }
            catch {
                resolve({});
            }
        });
    });
}
if (process.argv.includes("--smoke-test")) {
    const tickets = loadTickets();
    console.log(JSON.stringify({ app: "helpdesk-ticket-api-typescript", tickets: tickets.length }, null, 2));
    process.exit(0);
}
const port = Number(process.env.PORT || 3100);
const server = http.createServer(async (req, res) => {
    const requestUrl = new URL(req.url || "/", `http://localhost:${port}`);
    const pathname = requestUrl.pathname;
    const method = req.method || "GET";
    if (method === "GET" && pathname === "/health") {
        return writeJson(res, 200, {
            app: "helpdesk-ticket-api-typescript",
            status: "ok",
            ...metrics(loadTickets()),
        });
    }
    if (method === "GET" && pathname === "/tickets") {
        return writeJson(res, 200, loadTickets());
    }
    if (method === "GET" && pathname === "/metrics/summary") {
        return writeJson(res, 200, metrics(loadTickets()));
    }
    if (method === "POST" && pathname === "/tickets") {
        const body = await readBody(req);
        if (!body.title || !body.category || !body.priority || !body.owner) {
            return writeJson(res, 400, { error: "title, category, priority, owner wajib diisi" });
        }
        const tickets = loadTickets();
        const ticket = makeTicket(body.title, body.category, body.priority, body.owner, body.notes || "");
        tickets.unshift(ticket);
        saveTickets(tickets);
        return writeJson(res, 201, ticket);
    }
    if (pathname.startsWith("/tickets/")) {
        const id = pathname.split("/").pop();
        const tickets = loadTickets();
        const idx = tickets.findIndex((t) => t.id === id);
        if (method === "GET") {
            if (idx < 0)
                return writeJson(res, 404, { error: "Ticket tidak ditemukan" });
            return writeJson(res, 200, tickets[idx]);
        }
        if (method === "PATCH") {
            if (idx < 0)
                return writeJson(res, 404, { error: "Ticket tidak ditemukan" });
            const body = await readBody(req);
            tickets[idx] = { ...tickets[idx], ...body, updatedAt: now() };
            saveTickets(tickets);
            return writeJson(res, 200, tickets[idx]);
        }
        if (method === "DELETE") {
            if (idx < 0)
                return writeJson(res, 404, { error: "Ticket tidak ditemukan" });
            tickets.splice(idx, 1);
            saveTickets(tickets);
            return writeJson(res, 200, { ok: true });
        }
    }
    return writeJson(res, 404, { error: "Route tidak ditemukan" });
});
server.listen(port, () => {
    console.log(`Helpdesk Ticket API berjalan di http://localhost:${port}`);
});
