import { Database } from "bun:sqlite";
import express from "express";
import cors from "cors";
import * as path from "node:path";

const app = express();
const PORT = 21816;
const EXE_DIR = path.dirname(process.execPath);
const DB_NAME = "leye.db";
const DB_PATH = path.join(EXE_DIR, DB_NAME)

const db = new Database(DB_PATH, { create: true });
db.run(`
    CREATE TABLE IF NOT EXISTS leye_list_free (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT,
        type INTEGER,
        value TEXT,
        footprint INTEGER,
        brand INTEGER,
        info TEXT,
        quantity INTEGER,
        description TEXT,
        doc TEXT,
        lcscId TEXT
    )
`);

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

app.get("/api/getVersion", (req, res) => {
	res.json({ version: "1.0.0" });
});

app.get("/api/getLeyeList", (req, res) => {
	const params = req.query;
	let sql = "SELECT * FROM leye_list_free WHERE 1=1";
	let args = [];

	if (params.id) { sql += " AND id = ?"; args.push(params.id); }
	if (params.name) { sql += " AND name LIKE ?"; args.push(`%${params.name}%`); }
	if (params.type) { sql += " AND type = ?"; args.push(params.type); }
	if (params.value) { sql += " AND value LIKE ?"; args.push(`%${params.value}%`); }
	if (params.footprint) { sql += " AND footprint = ?"; args.push(params.footprint); }
	if (params.brand) { sql += " AND brand = ?"; args.push(params.brand); }
	if (params.quantity) { sql += " AND quantity >= ?"; args.push(params.quantity); }
	if (params.lcscId) { sql += " AND lcscId = ?"; args.push(params.lcscId); }

	try {
		const rows = db.query(sql).all(...args);
		res.json({ data: rows, total: rows.length, success: true });
	} catch (e) {
		res.status(500).json({ success: false, error: e.message });
	}
});

app.get("/api/getLcscOrder", async (req, res) => {
	const uuid = req.headers['x-uuid'] || req.headers['X-Uuid'];
	const cookies = req.headers['x-cookies'] || req.headers['X-Cookies'];
	let warehouse;

	if (!uuid || !cookies) {
		return res.status(400).json({
			success: false,
			error: "Missing required headers"
		});
	}

	try {
		const response = await fetch(`https://order-api.szlcsc.com/member/order/details/latest/process?orderUuid=${uuid}`, {
			headers: {
				"accept": "application/json",
				"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
				"cache-control": "no-cache",
				"pragma": "no-cache",
				"priority": "u=1, i",
				"sec-ch-ua": "\"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"144\", \"Microsoft Edge\";v=\"144\"",
				"sec-ch-ua-mobile": "?0",
				"sec-ch-ua-platform": "\"Windows\"",
				"sec-fetch-dest": "empty",
				"sec-fetch-mode": "cors",
				"sec-fetch-site": "same-site",
				"cookie": cookies,
				"Referer": "https://member.szlcsc.com/ "
			},
			method: "GET"
		});

		if (!response.ok) {
			return res.status(response.status).json({
				success: false,
				error: `LCSC API returned ${response.status}`
			});
		}

		const data = await response.json();
		warehouse = data?.result?.warehouseCode === 'sz' ? 'zh' : 'js';
	} catch (error) {
		res.status(500).json({
			success: false,
			error: error.message
		});
		return;
	}

	try {
		const response = await fetch(`https://order-api.szlcsc.com/member/print/deliverynote/${warehouse === 'zh' ? 'z' : 'j'}?uuid=${encodeURIComponent(uuid)}&deliveryType=${warehouse}`, {
			headers: {
				"accept": "application/json",
				"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
				"cache-control": "no-cache",
				"pragma": "no-cache",
				"priority": "u=1, i",
				"sec-ch-ua": "\"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"144\", \"Microsoft Edge\";v=\"144\"",
				"sec-ch-ua-mobile": "?0",
				"sec-ch-ua-platform": "\"Windows\"",
				"sec-fetch-dest": "empty",
				"sec-fetch-mode": "cors",
				"sec-fetch-site": "same-site",
				"cookie": cookies,
				"Referer": "https://member.szlcsc.com/ "
			},
			method: "GET"
		});

		if (!response.ok) {
			return res.status(response.status).json({
				success: false,
				error: `LCSC API returned ${response.status}`
			});
		}

		const data = await response.json();
		res.json({ success: true, data });

	} catch (error) {
		res.status(500).json({
			success: false,
			error: error.message
		});
	}
});

app.post("/api/addLeyeList", (req, res) => {
	const { name, lcscId, quantity } = req.body;
	if (!lcscId || !quantity) return res.status(400).send("Missing params");

	try {
		const existing = db.query("SELECT id, quantity FROM leye_list_free WHERE lcscId = ?").get(lcscId);

		if (existing) {
			const newQuantity = existing.quantity + quantity;
			db.run("UPDATE leye_list_free SET quantity = ? WHERE id = ?", newQuantity, existing.id);
			res.json({ success: true, action: "updated", quantity: newQuantity });
		} else {
			db.run("INSERT INTO leye_list_free (name, lcscId, quantity) VALUES (?, ?, ?)", name, lcscId, quantity);
			res.json({ success: true, action: "inserted" });
		}
	} catch (e) {
		res.status(500).json({ success: false, error: e.message });
	}
});

app.post("/api/editLeyeList", (req, res) => {
	const { id, name, lcscId, quantity } = req.body;
	if (!id) return res.status(400).send("Missing params");

	try {
		const existing = db.query("SELECT id, name, lcscId, quantity FROM leye_list_free WHERE id = ?").get(id);

		if (!existing) {
			return res.status(404).json({ success: false, error: "Record not found" });
		}

		const hasChanges =
			(name !== undefined && name !== existing.name) ||
			(lcscId !== undefined && lcscId !== existing.lcscId) ||
			(quantity !== undefined && quantity !== existing.quantity);

		if (hasChanges) {
			const updates = [];
			const params = [];

			if (name !== undefined && name !== existing.name) {
				updates.push("name = ?");
				params.push(name);
			}
			if (lcscId !== undefined && lcscId !== existing.lcscId) {
				updates.push("lcscId = ?");
				params.push(lcscId);
			}
			if (quantity !== undefined && quantity !== existing.quantity) {
				updates.push("quantity = ?");
				params.push(quantity);
			}

			if (updates.length > 0) {
				params.push(id);
				const sql = `UPDATE leye_list_free SET ${updates.join(", ")} WHERE id = ?`;
				db.query(sql).run(...params);
			}
		}

		res.json({
			success: true,
			updated: hasChanges,
			message: hasChanges ? "Updated successfully" : "No changes needed"
		});

	} catch (e) {
		res.status(500).json({ success: false, error: e.message });
	}
});

app.listen(PORT, "0.0.0.0", () => {
	console.log(`LEYE 免费扩展版服务端已启动`);
	console.log(`按 Ctrl+C 终止`);
});
