const express = require("express");
const User = require("../models/User");
const Street = require("../models/Street");
const auth = require("../middleware/auth");
const { asyncHandler } = require("../middleware/errorHandler");
const { userIdValidation } = require("../middleware/validators/userValidator");

const router = express.Router();

// Get user by ID
router.get(
  "/:id",
  auth,
  userIdValidation,
  asyncHandler(async (req, res) => {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ msg: "User not found" });
    }

    // Get adopted streets data
    let adoptedStreets = [];
    if (user.adoptedStreets && user.adoptedStreets.length > 0) {
      adoptedStreets = await Promise.all(
        user.adoptedStreets.map(async (streetId) => {
          const street = await Street.findById(streetId);
          return street ? {
            _id: street._id,
            name: street.name,
            location: street.location,
            status: street.status,
          } : null;
        })
      );
      adoptedStreets = adoptedStreets.filter(Boolean);
    }

    const userWithStreets = {
      ...user.toSafeObject(),
      adoptedStreets,
    };

    res.json(userWithStreets);
  }),
);

module.exports = router;
