import home from "./front/index.html";
import play from "./front/play.html";
import privacy from "./front/privacy.html";
import rules from "./front/rules.html";
import support from "./front/support.html";
import { apiRoutes } from "./server/api";
import { handleSocketMessage, registerSocket, unregisterSocket } from "./server/websocket";

const appleAppSiteAssociation = Bun.file("./.well-known/apple-app-site-association");
const assetLinks = Bun.file("./.well-known/assetlinks.json");

const server = Bun.serve({
	routes: {
		"/.well-known/apple-app-site-association": new Response(appleAppSiteAssociation, {
			headers: { "Content-Type": "application/json" },
		}),
		"/.well-known/assetlinks.json": new Response(assetLinks, {
			headers: { "Content-Type": "application/json" },
		}),
		"/": home,
		"/privacy": privacy,
		"/rules": Response.redirect("/rules/basics"),
		"/rules/:tab": rules,
		"/support": support,
		"/play": play,
		"/play/:sessionId": play,
		"/play/:sessionId/lobby": play,
		"/play/:sessionId/banker": play,
		"/play/:sessionId/banker/:tab": play,
		"/play/:sessionId/player": play,
		"/play/:sessionId/player/:tab": play,
		"/play/:sessionId/chat": play,
		"/play/:sessionId/chat/new": play,
		"/play/:sessionId/chat/:chatId": play,
		...apiRoutes,
	},
	fetch(req, server) {
		const url = new URL(req.url);
		if (url.pathname === "/ws") {
			const sessionId = url.searchParams.get("sessionId");
			const playerId = url.searchParams.get("playerId");
			if (!sessionId || !playerId) {
				return new Response("Missing sessionId or playerId", { status: 400 });
			}
			const upgraded = server.upgrade(req, {
				data: { sessionId, playerId },
			});
			if (upgraded) {
				return;
			}
			return new Response("Unable to upgrade", { status: 400 });
		}

		return new Response("Not found", { status: 404 });
	},
	websocket: {
		open(ws) {
			const { sessionId, playerId } = ws.data as {
				sessionId: string;
				playerId: string;
			};
			registerSocket(ws, sessionId, playerId);
		},
		message(ws, message) {
			handleSocketMessage(ws, message);
		},
		close(ws) {
			unregisterSocket(ws);
		},
	},
	development: {
		hmr: true,
		console: true,
	},
});

console.log(`Listening on ${server.url}`);
