import { handleHealth } from "./routes/health.ts";
import { handleLogin } from "./routes/login.ts";
import { handleStorage } from "./routes/storage.ts";

// db is initialized via side-effects when its imports are resolved
await import("./db.ts");

const PORT = parseInt(process.env.PORT ?? "3001");

const router = async (req: Request): Promise<Response> => {
    const url = new URL(req.url);
    console.log(`${req.method} ${url.pathname}`);
    // Split and strip empty segments so any prefix before /api is ignored.
    // lastIndexOf so the rightmost /api segment is the routing boundary.
    const segments = url.pathname.split("/").filter(Boolean);
    const apiIdx = segments.lastIndexOf("api");
    if (apiIdx === -1) {
        return Response.json({ error: "Not found" }, { status: 404 });
    }

    const [resource, ...rest] = segments.slice(apiIdx + 1);

    switch (resource) {
        case "health":
            return handleHealth(req);
        case "login":
            return handleLogin(req);
        case "storage": {
            const key = rest.join("/");
            return handleStorage(req, key);
        }
        default:
            return Response.json({ error: "Not found" }, { status: 404 });
    }
};

Bun.serve({
    port: PORT,
    fetch: router,
});

console.log(`tsgames-backend listening on port ${PORT}`);
