const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");
require("dotenv").config();

module.exports = {
  getAll,
  filter,
  option,
  count,
  create,
  update,
  enabled,
  delete: _delete,
};

async function getAll() {
  try {
    const outletTypes = await dbSAPPS.OutletType.findAll({
      order: [["modified", "DESC"]],
    });

    return {
      outletTypes,
      success: true,
      message: "Outlet Types loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to load Outlet Types!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  const filterConditions = {};
  
  // Handle 'f_' prefix from frontend table filters
  const cleanParams = { ...params };
  Object.keys(cleanParams).forEach((key) => {
    if (key.startsWith("f_")) {
      cleanParams[key.substring(2)] = cleanParams[key];
    }
  });

  if (cleanParams.q) {
    filterConditions[Op.or] = [
      { display_name: { [Op.like]: `%${cleanParams.q}%` } },
      { code: { [Op.like]: `%${cleanParams.q}%` } },
      { slug: { [Op.like]: `%${cleanParams.q}%` } },
    ];
  }

  if (cleanParams.display_name) {
    filterConditions.display_name = {
      [Op.like]: `%${cleanParams.display_name}%`,
    };
  }
  if (cleanParams.code) {
    filterConditions.code = {
      [Op.like]: `%${cleanParams.code}%`,
    };
  }
  if (cleanParams.slug) {
    filterConditions.slug = {
      [Op.like]: `%${cleanParams.slug}%`,
    };
  }
  if (cleanParams.enabled) {
    filterConditions.enabled = {
      [Op.eq]: cleanParams.enabled === "1" ? true : false,
    };
  }
  try {
    const outletTypes = await dbSAPPS.OutletType.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
    });

    return {
      success: true,
      outletTypes,
      message: "Outlet Types loaded successfully!",
    };
  } catch (error) {
    console.error("Error retrieving Outlet Types: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Outlet Types. Please try again later.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option() {
  try {
    const outletTypes = await dbSAPPS.OutletType.findAll({
      attributes: ["id", "display_name", "code", "slug"],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      outletTypes,
      message: "Outlet Types loaded successfully!",
    };
  } catch (error) {
    console.error("Error retrieving Outlet Types: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Outlet Types. Please try again later.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function count() {
  try {
    const count = await dbSAPPS.OutletType.count({
      where: { enabled: true },
    });

    return {
      success: true,
      count,
      message: "Outlet Types loaded successfully!",
    };
  } catch (error) {
    console.error("Error counting Outlet Types: ", error);
    return {
      success: false,
      message: "Failed to retrieve Outlet Types count. Please try again later.",
    };
  }
}

async function create(params) {
  try {
    if (!params.display_name || !params.code || !params.slug)
      return {
        success: false,
        message: "Outlet Types name , code, slug are required!",
      };

    const existingNameNNumber = await dbSAPPS.OutletType.findOne({
      where: {
        display_name: params.display_name,
        code: params.code,
        slug: params.slug,
      },
    });
    if (existingNameNNumber)
      return {
        success: false,
        message: `Outlet Type name "${params.display_name}", code "${params.code}", and slug "${params.slug} is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newOutletTypes = await dbSAPPS.OutletType.create(params);

    return {
      success: true,
      message: "Outlet Types data has been successfully added!",
      outletTypes: newOutletTypes,
    };
  } catch (error) {
    const errorMessage =
      error.message || "An error occurred during create Outlet Types processing.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function update(id, params) {
  try {
    // Ambil dari database
    const outletTypes = await dbSAPPS.OutletType.findByPk(id);
    if (!outletTypes)
      return {
        success: false,
        message: "Outlet Type not found!",
      };

    if (params.display_name && params.display_name !== outletTypes.display_name) {
      const existingOutletTypeName = await dbSAPPS.OutletType.findOne({
        where: { display_name: params.display_name },
      });
      if (existingOutletTypeName) {
        return {
          success: false,
          message: `Outlet Type name "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    if (params.code && params.code !== outletTypes.code) {
      const existingOutletTypeCode = await dbSAPPS.OutletType.findOne({
        where: { code: params.code },
      });
      if (existingOutletTypeCode) {
        return {
          success: false,
          message: `Outlet Type code "${params.code}" is already taken. Try again!`,
        };
      }
    }

    if (params.slug && params.slug !== outletTypes.slug) {
      const existingOutletTypeSlug = await dbSAPPS.OutletType.findOne({
        where: { slug: params.slug },
      });
      if (existingOutletTypeSlug) {
        return {
          success: false,
          message: `Outlet Type slug "${params.slug}" is already taken. Try again!`,
        };
      }
    }

    await outletTypes.update(params);

    return {
      success: true,
      message: "Data Outlet Type has been saved!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update Outlet Type data.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function enabled(id, params) {
  try {
    const outletTypes = await dbSAPPS.OutletType.findByPk(id);
    if (!outletTypes)
      return {
        success: false,
        message: "Outlet Type not found!",
      };

    const updateData = {};
    updateData.enabled = params.enabled;
    if (params.modified_by) updateData.modified_by = params.modified_by;
    if (params.modified) updateData.modified = params.modified;

    await outletTypes.update(updateData);

    return {
      success: true,
      message: "Outlet Type has been updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update Outlet Type.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function _delete(id) {
  try {
    const outletTypes = await dbSAPPS.OutletType.findByPk(id);
    if (!outletTypes) return { success: false, message: "Outlet Type not found!" };

    await outletTypes.destroy();

    return {
      success: true,
      message: "Outlet Type successfully deleted!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to delete Outlet Type.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}
