import express from "express";
import multer from "multer";
import { PTW_MAX_UPLOAD_BYTES } from "../constants/uploadLimits.js";
import { ApiError } from "../utils/ApiError.js";
import { createCrudRouter } from "./crudRouter.js";
import {
  listPermits,
  getPermit,
  createPermit,
  updatePermit,
  deletePermit
} from "../controllers/ptwPermitController.js";
import { getDashboardStats } from "../controllers/ptwDashboardController.js";
import {
  createSubmission,
  getSubmissionAnswers,
  listAnswersMedia,
  serveAnswerMedia,
  submitFormSection
} from "../controllers/ptwSubmissionController.js";
import {
  listMyHandoverNotifications,
  markAllHandoverNotificationsRead,
  markHandoverNotificationRead
} from "../controllers/ptwNotificationController.js";

const router = express.Router();

// In-memory upload for answer media → straight into LONGBLOB.
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: PTW_MAX_UPLOAD_BYTES }
});

function handleUpload(req, res, next) {
  upload.any()(req, res, (err) => {
    if (!err) return next();
    if (err?.code === "LIMIT_FILE_SIZE") {
      return next(
        new ApiError(
          400,
          `A file exceeds the ${PTW_MAX_UPLOAD_BYTES / (1024 * 1024)} MB upload limit. Use a shorter or lower-resolution video.`
        )
      );
    }
    next(new ApiError(400, err.message || "File upload failed"));
  });
}

// Permits: dedicated controller (auto permit_number, status transitions).
router.get("/dashboard/stats", getDashboardStats);
router.get("/notifications/handover", listMyHandoverNotifications);
router.patch("/notifications/handover/read-all", markAllHandoverNotificationsRead);
router.patch("/notifications/handover/:notification_id/read", markHandoverNotificationRead);
router.get("/ptw_permits", listPermits);
router.get("/ptw_permits/:permit_id", getPermit);
router.post("/ptw_permits", createPermit);
router.put("/ptw_permits/:permit_id", updatePermit);
router.delete("/ptw_permits/:permit_id", deletePermit);

// Submission ingestion (answers + media + opening/closing linkage).
router.post("/submissions", handleUpload, createSubmission);
router.post("/submissions/section", handleUpload, submitFormSection);
router.get("/submissions/:submission_id/answers", getSubmissionAnswers);
router.get("/ptw_answers_media/:answers_id/:occurrence/file", serveAnswerMedia);
router.get("/ptw_answers_media", listAnswersMedia);

// Generic CRUD for submission-related tables.
router.use("/ptw_submissions", createCrudRouter("ptw_submissions", ["submission_id"]));
router.use(
  "/ptw_opening_closing_map",
  createCrudRouter("ptw_opening_closing_map", ["permit_id", "opening_sub_id"])
);
router.use("/ptw_answers", createCrudRouter("ptw_answers", ["answers_id"]));
router.use(
  "/ptw_answers_media",
  createCrudRouter("ptw_answers_media", ["answers_id", "occurrence"])
);

export default router;
