const express = require("express");
const GridCell = require("../schemas/GridCell");

const router = express.Router();

let io;
router.setIO = (_io) => {
  io = _io;
};

// GET /api/grid-cells
router.get("/", async (req, res) => {
  try {
    const { minx, miny, maxx, maxy } = req.query;
    if (minx != null && miny != null && maxx != null && maxy != null) {
      const query = {};
      if (minx !== "" && !isNaN(parseInt(minx))) query.x = { $gte: parseInt(minx) };
      if (miny !== "" && !isNaN(parseInt(miny))) query.y = { $gte: parseInt(miny) };
      if (maxx !== "" && !isNaN(parseInt(maxx))) {
        query.x = query.x || {};
        query.x.$lte = parseInt(maxx);
      }
      if (maxy !== "" && !isNaN(parseInt(maxy))) {
        query.y = query.y || {};
        query.y.$lte = parseInt(maxy);
      }
      const cells = await GridCell.find(query)
        .sort({ x: 1, y: 1 })
        .limit(10000)
        .lean();
      return res.json(cells);
    }
    const limit = Math.min(parseInt(req.query.limit) || 1000, 1000);
    const cells = await GridCell.find()
      .sort({ x: 1, y: 1 })
      .limit(limit)
      .lean();
    res.json(cells);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

// POST /api/grid-cells/paint — upsert (create or update a grid cell)
router.post("/paint", async (req, res) => {
  console.log("Hola")
  try {
    const { x, y, color } = req.body;
    if (x == null || y == null || color == null)
      return res.status(400).json({ error: "x, y, and color are required" });
    const validated = await GridCell.findOneAndUpdate(
      { x, y },
      { x, y, color },
      { returnDocument: 'after', upsert: true }
    );
    
    if (io) {
      io.emit("grid-cell-paint", { x, y, color });
    }
    
    res.json(validated);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
});

module.exports = router;
