const express = require("express");
const UserCase = require("../models/userCaseModel");
const Case = require("../models/caseModel");
const User = require("../models/userModel");
const { Form } = require("../models");

const assignedCase = async (req, res) => {
  const userId = req.user.id;

  try {
    const user = await User.findByPk(userId);
    if (!user || user.isdeleted === 1) {
      return res.status(200).json({
        status: false,
        message: "User not found",
      });
    }
    if (user.role === "admin") {
      return res.status(200).json({
        status: false,
        message: "You are not authorized to view assigned cases",
      });
    }
    const assignedCases = await UserCase.findAll({
      where: { userId: userId, isDeleted: 0 },
      include: [
        {
          model: Case,
          attributes: ["id", "title", "file_path"],
        },
        {
          model: User,
          attributes: ["id", "username"],
        },
      ],
      order: [["assignedAt", "DESC"]],
    });
    const baseUrl = req.protocol + "://" + req.get("host");
    const data = assignedCases.map((row) => {
      const obj = row.toJSON();

      const p = obj?.Case?.file_path || null;
      if (p) {
        // normalize backslashes, avoid double slashes, and encode spaces/etc.
        const normalized = p.replace(/\\/g, "/");
        const noLeading = normalized.startsWith("/")
          ? normalized.slice(1)
          : normalized;
        obj.Case.fileUrl = `${baseUrl}/${encodeURI(noLeading)}`;
      } else {
        obj.Case.fileUrl = null;
      }

      delete obj.Case.file_path; // remove the original field
      return obj;
    });
    const assignCaseForm = await Form.findAll({
      where: { userId: userId, isDeleted: 0 },
    });
    //  console.log("assignCaseForm",assignCaseForm);

    const mapAssignCaseForm = assignCaseForm.map((item) => {
      return {
        caseId: item.caseId,
        formId: item.id,
        status: item.status,
      };
    });
    if (assignedCases.length === 0) {
      return res.status(200).json({
        status: false,
        message: "No assigned cases",
      });
    }

    return res.status(200).json({
      status: true,
      data: {
        message: "Assigned cases retrieved successfully",
        data: data,
        assignCaseForm: mapAssignCaseForm,
      },
    });
  } catch (error) {
    console.error("Error in assigned cases: ", error);
    return res.status(200).json({
      status: false,
      message: "Something went wrong",
      error: error.message,
    });
  }
};

const totalAssignedCases = async (req, res) => {
  const userId = req.user.id;

  try {
    const user = await User.findByPk(userId);
    if (!user || user.isdeleted === 1) {
      return res.status(200).json({
        status: false,
        message: "User not found",
      });
    }
    if (user.role === "admin") {
      return res.status(200).json({
        status: false,
        message: "You are not authorized to view total assigned cases",
      });
    }
    const assignedCases = await UserCase.findAll({
      where: { userId: userId },
    });

    if (assignedCases.length === 0) {
      return res.status(200).json({
        status: false,
        message: "No assigned cases found",
      });
    }

    return res.status(200).json({
      status: true,
      data: {
        message: "Total assigned cases retrieved successfully",
        response: assignedCases.length,
      },
    });
  } catch (error) {
    console.error("Error in total assigned cases: ", error);
    return res.status(200).json({
      status: false,
      message: "Something went wrong",
      error: error.message,
    });
  }
};

module.exports = {
  assignedCase,
  totalAssignedCases,
};
