import { Router } from "express";
import { getDb } from "../../src/db";
import { authenticateToken } from "../../src/middleware/auth.middleware";
import {
  abandonTowerSimulation,
  createTowerSimulation,
  getTowerCatalog,
  getTowerProgress,
  getTowerSimulation,
  listTowerSimulations,
} from "./coreGameplayEngine";
import { buildTowerBattlePayload } from "./towerBattleAdapter";

export const coreGameplayRouter = Router();

coreGameplayRouter.get("/tower/catalog", authenticateToken, async (_req: any, res) => {
  try {
    const db = await getDb();
    const catalog = await getTowerCatalog(db);
    res.json(catalog);
  } catch (error) {
    console.error("Tower catalog error:", error);
    res.status(500).json({ error: "Failed to fetch tower catalog." });
  }
});

coreGameplayRouter.get("/tower/progress", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const progress = await getTowerProgress(db, req.user.id);
    res.json(progress);
  } catch (error) {
    console.error("Tower progress error:", error);
    res.status(500).json({ error: "Failed to fetch tower progress." });
  }
});

coreGameplayRouter.get("/tower/simulations", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const limit = req.query?.limit;
    const simulations = await listTowerSimulations(db, req.user.id, limit);
    res.json({ simulations });
  } catch (error) {
    console.error("Tower simulation list error:", error);
    res.status(500).json({ error: "Failed to fetch tower simulations." });
  }
});

coreGameplayRouter.get("/tower/simulations/:simulationId", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const simulation = await getTowerSimulation(db, req.user.id, req.params.simulationId);
    if (!simulation) {
      return res.status(404).json({ error: "Simulation not found." });
    }
    res.json({ simulation });
  } catch (error) {
    console.error("Tower simulation fetch error:", error);
    res.status(500).json({ error: "Failed to fetch tower simulation." });
  }
});

coreGameplayRouter.post("/tower/simulations", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const result = await createTowerSimulation(db, req.user.id, {
      gameMode: req.body?.gameMode,
      domainId: req.body?.domainId,
      sectorId: req.body?.sectorId,
      floorId: req.body?.floorId,
      roomId: req.body?.roomId,
      seed: req.body?.seed,
    });

    if (!result.ok) {
      return res.status(400).json(result);
    }

    res.status(201).json(result);
  } catch (error) {
    console.error("Tower simulation create error:", error);
    res.status(500).json({ error: "Failed to create tower simulation." });
  }
});

coreGameplayRouter.post("/tower/simulations/:simulationId/abandon", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const result = await abandonTowerSimulation(
      db,
      req.user.id,
      req.params.simulationId,
      req.body?.reason || "abandoned"
    );

    if (!result.ok) {
      return res.status(result.code === "SIMULATION_NOT_FOUND" ? 404 : 409).json(result);
    }

    res.json(result);
  } catch (error) {
    console.error("Tower simulation abandon error:", error);
    res.status(500).json({ error: "Failed to abandon tower simulation." });
  }
});

coreGameplayRouter.get("/tower/simulations/:simulationId/battle-payload", authenticateToken, async (req: any, res) => {
  try {
    const db = await getDb();
    const payload = await buildTowerBattlePayload(db, req.user.id, req.params.simulationId);
    if (!payload) {
      return res.status(404).json({ error: "Simulation not found." });
    }
    res.json(payload);
  } catch (error) {
    console.error("Tower battle payload error:", error);
    res.status(500).json({ error: "Failed to build tower battle payload." });
  }
});
