const express = require("express");
const { authenticateToken } = require("../middleware/auth");
const ConditionCheckService = require("../services/conditionCheckService");
const logger = require("../utils/logger");
const { validateS3Keys } = require("../utils/s3KeyValidator");
const { IMAGE_LIMITS } = require("../config/imageLimits");

const router = express.Router();

// Get condition checks for multiple rentals in a single request (batch)
router.get("/batch", authenticateToken, async (req, res) => {
  try {
    const { rentalIds } = req.query;

    if (!rentalIds) {
      return res.json({
        success: true,
        conditionChecks: [],
      });
    }

    const ids = rentalIds.split(",").filter((id) => id.trim());

    if (ids.length === 0) {
      return res.json({
        success: true,
        conditionChecks: [],
      });
    }

    const conditionChecks =
      await ConditionCheckService.getConditionChecksForRentals(ids);

    res.json({
      success: true,
      conditionChecks,
    });
  } catch (error) {
    const reqLogger = logger.withRequestId(req.id);
    reqLogger.error("Error fetching batch condition checks", {
      error: error.message,
      stack: error.stack,
      rentalIds: req.query.rentalIds,
    });

    res.status(500).json({
      success: false,
      error: "Failed to fetch condition checks",
    });
  }
});

// Submit a condition check
router.post("/:rentalId", authenticateToken, async (req, res) => {
  try {
    const { rentalId } = req.params;
    const { checkType, notes, imageFilenames: rawImageFilenames } = req.body;
    const userId = req.user.id;

    // Ensure imageFilenames is an array (S3 keys)
    const imageFilenamesArray = Array.isArray(rawImageFilenames)
      ? rawImageFilenames
      : [];

    // Validate S3 keys format and folder
    const keyValidation = validateS3Keys(
      imageFilenamesArray,
      "condition-checks",
      {
        maxKeys: IMAGE_LIMITS.conditionChecks,
      }
    );
    if (!keyValidation.valid) {
      return res.status(400).json({
        success: false,
        error: keyValidation.error,
        details: keyValidation.invalidKeys,
      });
    }

    const imageFilenames = imageFilenamesArray;

    const conditionCheck = await ConditionCheckService.submitConditionCheck(
      rentalId,
      checkType,
      userId,
      imageFilenames,
      notes
    );

    const reqLogger = logger.withRequestId(req.id);
    reqLogger.info("Condition check submitted", {
      rentalId,
      checkType,
      userId,
      photoCount: imageFilenames.length,
    });

    res.status(201).json({
      success: true,
      conditionCheck,
    });
  } catch (error) {
    const reqLogger = logger.withRequestId(req.id);
    reqLogger.error("Error submitting condition check", {
      error: error.message,
      stack: error.stack,
      rentalId: req.params.rentalId,
      userId: req.user?.id,
    });

    res.status(400).json({
      success: false,
      error: error.message,
    });
  }
});

// Get available condition checks for current user
router.get("/", authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { rentalIds } = req.query;
    const ids = rentalIds ? rentalIds.split(",").filter((id) => id.trim()) : [];

    const availableChecks = await ConditionCheckService.getAvailableChecks(
      userId,
      ids
    );

    res.json({
      success: true,
      availableChecks,
    });
  } catch (error) {
    const reqLogger = logger.withRequestId(req.id);
    reqLogger.error("Error fetching available checks", {
      error: error.message,
      stack: error.stack,
      userId: req.user?.id,
    });

    res.status(500).json({
      success: false,
      error: "Failed to fetch available checks",
    });
  }
});

module.exports = router;
