import { Router } from "express";
// import { genSalt, hash, compare } from "bcryptjs";
// import jwt from "jsonwebtoken";
import passport from "passport";
// import User from "../models/user.js";
import mongoose from "mongoose";
import Verification from "../models/verification.js";
import ImageDetection from "../models/image-detections.js";
import "dotenv/config";

const router = Router();

router.post(
  "/verification",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const { imageId, patientId, doctorId, patientNotes } = req.body;
      const imageObjectId = new mongoose.Types.ObjectId(imageId);
      const newVerification = new Verification({
        imageId: imageObjectId,
        patientId,
        doctorId,
        patientNotes,
        verificationRequested: true,
      });

      await newVerification.save();
      await ImageDetection.findByIdAndUpdate(
        imageId,
        { verification: newVerification._id }, // Set verifiedStatus to the Verification document _id
        { new: true },
      );

      res.status(201).json(newVerification);
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  },
);

router.patch(
  "/verificating/:id",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const { id } = req.params;
      const { doctorNotes, verifiedStatus } = req.body;

      const verification = await Verification.findByIdAndUpdate(
        id,
        { doctorNotes, verifiedStatus },
        { new: true },
      );

      if (!verification)
        return res.status(404).json({ message: "User verification not found" });

      res.status(200).json({
        message: "Verification has been done successfully",
        verification,
      });
    } catch (err) {
      console.error(err);
      res.status(500).json({ message: "Failed to upload verification" });
    }
  },
);

export default router;
