import response from "../../response.js";
import models from "../../models/index.js";

export const getReports = async (req, res) => {
  const { page = 1, limit = 10, search = "", sort = "time" } = req.query;

  try {
    const { count, rows: reports } = await models.Report.findAndCountAll({
      include: [
        {
          model: models.User,
          as: "reportUser",
          attributes: ["NAME_USERS", "EMAIL"],
        },
      ],
      where: {
        ...(search && {
          [models.Op.or]: [
            {
              "$reportUser.NAME_USERS$": {
                [models.Op.like]: `%${search}%`,
              },
            },
            {
              "$reportUser.EMAIL$": {
                [models.Op.like]: `%${search}%`,
              },
            },
            {
              REPORTS: {
                [models.Op.like]: `%${search}%`,
              },
            },
          ],
        }),
      },
      distinct: true,
      order: [
        sort === "email"
          ? [{ model: models.User, as: "reportUser" }, "EMAIL", "ASC"]
          : sort === "name"
          ? [{ model: models.User, as: "reportUser" }, "NAME_USERS", "ASC"]
          : sort === "report"
          ? ["REPORTS", "ASC"]
          : ["TIME_REPORT", "DESC"],
      ],
      limit: parseInt(limit),
      offset: (page - 1) * limit,
    });

    const modifiedReports = reports.map((report) => {
      const reportData = report.toJSON();
      reportData.USER_NAME = reportData.reportUser.NAME_USERS;
      reportData.USER_EMAIL = reportData.reportUser.EMAIL;
      delete reportData.reportUser;
      return reportData;
    });

    const totalPages = Math.ceil(count / limit);
    const currentPage = parseInt(page);

    response(
      200,
      {
        reports: modifiedReports,
        currentPage,
        totalPages,
        totalItems: count,
      },
      "Reports retrieved successfully",
      res
    );
  } catch (error) {
    console.log(error);
    response(500, null, "Error retrieving reports data!", res);
  }
};

export const getFiveNewReports = async (req, res) => {
  try {
    const reports = await models.Report.findAll({
      include: [
        {
          model: models.User,
          as: "reportUser",
          attributes: ["NAME_USERS", "EMAIL"],
        },
      ],
      order: [["TIME_REPORT", "DESC"]],
      limit: 5,
    });

    const modifiedReports = reports.map((report) => {
      const reportData = report.toJSON();
      reportData.USER_NAME = reportData.reportUser.NAME_USERS;
      reportData.USER_EMAIL = reportData.reportUser.EMAIL;
      delete reportData.reportUser;
      return reportData;
    });

    response(
      200,
      modifiedReports,
      "Five latest reports retrieved successfully",
      res
    );
  } catch (error) {
    console.error(error);
    response(500, null, "Error retrieving the latest reports", res);
  }
};

export const getReportById = async (req, res) => {
  try {
    const { id } = req.params;
    const report = await models.Report.findByPk(id, {
      include: [
        {
          model: models.User,
          as: "reportUser",
          attributes: ["NAME_USERS", "EMAIL"],
        },
      ],
    });

    if (!report) {
      return response(404, null, "Report data not found", res);
    }

    const reportData = report.toJSON();
    reportData.USER_NAME = reportData.reportUser.NAME_USERS;
    reportData.USER_EMAIL = reportData.reportUser.EMAIL;

    delete reportData.reportUser;

    response(200, reportData, "Success", res);
  } catch (error) {
    console.log(error);
    response(500, null, "Internal Server Error", res);
  }
};

export const getReportForAdmin = async (req, res) => {};

export const getReportByUserId = async (req, res) => {
  try {
    const { id } = req.params;

    const reports = await models.Report.findAll({
      where: { ID: id },
      include: [
        {
          model: models.User,
          as: "reportUser",
          attributes: ["NAME_USERS", "EMAIL"],
        },
      ],
    });

    if (reports.length === 0) {
      return response(404, null, "No report data found for this user", res);
    }

    const modifiedReports = reports.map((report) => {
      const reportData = report.toJSON();

      reportData.USER_NAME = reportData.reportUser.NAME_USERS;
      reportData.USER_EMAIL = reportData.reportUser.EMAIL;

      delete reportData.reportUser;

      return reportData;
    });

    response(200, modifiedReports, "Success", res);
  } catch (error) {
    console.log(error);
    response(500, null, "Internal Server Error", res);
  }
};

export const userReport = async (req, res) => {
  if (!req.user) {
    return response(401, null, "User not authenticated", res);
  }

  const { REPORTS } = req.body;

  if (!REPORTS || REPORTS.trim() === "") {
    return response(400, null, "Report content is required", res);
  }

  try {
    const newReport = await models.Report.create({
      ID: req.user.ID,
      REPORTS: REPORTS,
    });

    const createdReport = await models.Report.findByPk(newReport.ID_REPORT, {
      include: [
        {
          model: models.User,
          as: "reportUser",
          attributes: ["NAME_USERS", "EMAIL"],
        },
      ],
    });

    const reportData = createdReport.toJSON();
    reportData.USER_NAME = reportData.reportUser.NAME_USERS;
    reportData.USER_EMAIL = reportData.reportUser.EMAIL;

    delete reportData.reportUser;

    response(201, reportData, "Report created successfully", res);
  } catch (error) {
    console.error(error);
    response(500, null, "Internal Server Error", res);
  }
};

export const deleteReportById = async (req, res) => {
  const { id } = req.params;

  try {
    const report = await models.Report.findByPk(id);

    if (!report) {
      return response(404, null, "Report not found", res);
    }

    await report.destroy();

    response(200, null, "Report deleted successfully", res);
  } catch (error) {
    console.error(error);
    response(500, null, "Internal Server Error", res);
  }
};
