import express from "express";
import { loadConfig } from "./lib/config";
import { Selector } from "./lib/selector";
import http from "http";
import https from "https";
import fs from "fs";
import path from "path";

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

async function main() {
	const config = await loadConfig();
	const selector = new Selector(config);
	await selector.init();

	app.set("trust proxy", config.trustedProxies);



	app.get("/api/get", async (req: express.Request, res: express.Response) => {
		const addr = req.ip;
		const groups = await selector.get(addr);
		res.json({ ip: addr, title: config.title, groups });
	});

	app.post("/api/add", async (req: express.Request, res: express.Response) => {
		const addr = req.ip;
		const setname = req.body.setname;
		const result = await selector.add(addr, setname);
		res.json(result);
	});
	app.post("/api/del", async (req: express.Request, res: express.Response) => {
		const addr = req.ip;
		const setname = req.body.setname;
		const result = await selector.del(addr, setname);
		res.json(result);
	});

	const staticDir = path.join(__dirname, 'public');
	app.use(express.static(staticDir));
	app.get('/', (req: express.Request, res: express.Response) => {
		res.sendFile('index.html', { root: staticDir });
	});

	if (config.ssl) {
		const cert = await fs.promises.readFile(config.ssl.cert);
		const key = await fs.promises.readFile(config.ssl.key);
		const server = https.createServer({ cert, key }, app);
		server.listen(config.port, config.address);
	} else {
		const server = http.createServer(app);
		server.listen(config.port, config.address);
	}
}
main();
