import "dotenv/config";
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { createServer } from "http";
import { Server } from "socket.io";
import { setupSocket } from "./socket.js";
import { runMigrations } from "./migrate.js";
import { seedDevData } from "./seed-dev-data.js";
import campaignRoutes from "./routes/campaigns.js";
import characterRoutes from "./routes/characters.js";
import gameItemRoutes from "./routes/game-items.js";
import gameTalentRoutes from "./routes/game-talents.js";
import rollRoutes from "./routes/rolls.js";
import spellRoutes from "./routes/spells.js";
import authRoutes from "./routes/auth.js";
import db from "./db.js";

const CLIENT_URL = process.env.CLIENT_URL ?? "http://localhost:5173";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: { origin: CLIENT_URL, credentials: true },
});

app.use(cors({ origin: CLIENT_URL, credentials: true }));
app.use(express.json());
app.use(cookieParser());

app.set("io", io);

setupSocket(io);

app.use("/api/auth", authRoutes);
app.use("/api/campaigns", campaignRoutes);
app.use("/api/campaigns/:campaignId/characters", characterRoutes);
app.use("/api/characters", characterRoutes);
app.use("/api/game-items", gameItemRoutes);
app.use("/api/game-talents", gameTalentRoutes);
app.use("/api/campaigns/:campaignId/rolls", rollRoutes);
app.use("/api/spells", spellRoutes);

const PORT = process.env.PORT ?? 3000;

async function start() {
  await runMigrations(db);
  await seedDevData();
  httpServer.listen(PORT, () => {
    console.log(`Darkwatch server running on http://localhost:${PORT}`);
  });
}

start().catch((err) => {
  console.error("Failed to start server:", err);
  process.exit(1);
});

export { io };
