import express from "express";
import multer from "multer";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { createCrudRouter } from "./crudRouter.js";
import {
  listOracAssessments,
  listUserAssessmentsGroupedByStatus,
  uploadOracAssessment,
  assignExecutor,
  assignVerifier,
  assignAssessmentForm,
  executorSubmitForVerification,
  completeVerifierReview,
  returnToExecutorFromVerifier
} from "../controllers/oracAssessmentsUploadController.js";

const router = express.Router();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const uploadsDir = path.join(__dirname, "..", "..", "uploads", "videos");
fs.mkdirSync(uploadsDir, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const base = path.basename(file.originalname, ext);
    cb(null, `${Date.now()}-${base}${ext}`);
  }
});

const upload = multer({ storage });

router.post(
  "/orac_assessments/upload",
  upload.single("video"),
  uploadOracAssessment
);

router.post(
  "/orac_assessments/:assessment_id/assign_executor",
  assignExecutor
);

router.post(
  "/orac_assessments/:assessment_id/assign_verifier",
  assignVerifier
);

router.post(
  "/orac_assessments/:assessment_id/assign_form",
  assignAssessmentForm
);

router.post(
  "/orac_assessments/:assessment_id/executor_submit_for_verification",
  executorSubmitForVerification
);

router.post(
  "/orac_assessments/:assessment_id/verifier_complete",
  completeVerifierReview
);

router.post(
  "/orac_assessments/:assessment_id/verifier_return",
  returnToExecutorFromVerifier
);

// Match with or without trailing slash so clients using `/orac_assessments/` hit this handler, not generic CRUD `listRecords`.
router.get(["/orac_assessments", "/orac_assessments/"], listOracAssessments);
router.get(
  "/orac_assessments/user/:user_id/grouped_by_status",
  listUserAssessmentsGroupedByStatus
);

router.use(
  "/orac_assessments",
  createCrudRouter("orac_assessments", [
    "assessment_id",
    "uploader_user_id",
    "assessment_status_id"
  ])
);

export default router;


