const db = require('../db/models');
const ValidationError = require('./notifications/errors/validation');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

/**
 * @param {string} permission
 * @param {object} currentUser
 */
async function checkPermissions(permission, currentUser) {

  if (!currentUser) {
    throw new ValidationError('auth.unauthorized');
  }

  const userPermission = currentUser.custom_permissions.find(
    (cp) => cp.name === permission,
  );

  if (userPermission) {
    return true;
  }

  try {
    if (!currentUser.app_role) {
      throw new ValidationError('auth.forbidden');
    }

    const permissions = await currentUser.app_role.getPermissions();

    return !!permissions.find((p) => p.name === permission);
  } catch (e) {
    throw e;
  }
}

module.exports = class SearchService {
  static async search(searchQuery, currentUser) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {

            "users": [

                "firstName",

                "lastName",

                "phoneNumber",

                "email",

            ],

            "branches": [

                "code",

                "name",

                "description",

            ],

            "calendars": [

                "description",

                "flag",

            ],

            "client_status": [

                "name",

            ],

            "clients": [

                "code",

                "name_en",

                "name_kh",

                "phone_number",

                "document_number",

            ],

            "communes": [

                "name_kh",

                "name_en",

            ],

            "districts": [

                "name_kh",

                "name_en",

            ],

            "document_type": [

                "name",

            ],

            "expense_items": [

                "description",

            ],

            "expense_types": [

                "name_kh",

                "name_en",

            ],

            "group_menus": [

                "name",

            ],

            "guarantor": [

                "full_name",

                "document_type",

                "document_number",

                "phone_number",

                "full_address_input",

            ],

            "interest_rates": [

                "code",

                "name",

                "css",

                "setting",

            ],

            "loan_status": [

                "name",

                "css",

            ],

            "loan_types": [

                "name_kh",

                "name_en",

            ],

            "loans": [

                "code",

                "purpose",

            ],

            "members": [

                "name_kh",

                "name_en",

                "phone_number",

            ],

            "menus": [

                "label",

                "url",

                "active_url",

                "permission",

                "icon",

            ],

            "payment_status": [

                "name",

                "css",

            ],

            "payments": [

                "remark",

            ],

            "provinces": [

                "name_kh",

                "name_en",

            ],

            "sexes": [

                "name",

            ],

            "shareholders": [

                "name_en",

                "name_kh",

                "phone_number",

                "born_place",

                "document_type",

                "document_number",

                "emergency_number",

                "current_place",

            ],

            "staff_status": [

                "name",

                "css",

            ],

            "staffs": [

                "name_en",

                "name_kh",

                "phone_number",

                "born_place",

                "document_type",

                "document_number",

                "emergency_number",

                "current_place",

            ],

            "urls": [

                "uri",

                "route_name",

            ],

            "user_has_menu": [

                "status",

            ],

            "user_types": [

                "name",

            ],

            "villages": [

                "name_kh",

                "name_en",

            ],

      };
      const columnsInt = {

            "deposits": [

                "deposit_amount",

            ],

            "expense_items": [

                "expense_amount",

            ],

            "interest_rates": [

                "rate",

                "commission_rate",

                "interval",

                "sort",

            ],

            "loans": [

                "principal_amount",

                "term",

                "pending_amount",

                "last_pending_amount",

                "rate",

                "commission_rate",

                "finish_discount",

                "finish_discount_amount",

                "admin_rate",

                "admin_amount",

            ],

            "payment_revenues": [

                "admin_fee_amount",

                "interest_amount",

                "commission_amount",

                "expense_amount",

            ],

            "payment_transactions": [

                "transaction_amount",

                "deduct_amount",

                "interest_amount",

                "commission_amount",

                "revenue_amount",

            ],

            "payments": [

                "sort",

                "deduct_amount",

                "deduct_paid_amount",

                "interval",

                "interest_amount",

                "commission_amount",

                "total_amount",

                "total_paid_amount",

                "penalty_amount",

                "pending_amount",

                "cross_amount",

            ],

            "shareholders": [

                "earn_rate",

            ],

      };

      let allFoundRecords = [];

      for (const tableName in tableColumns) {
        if (tableColumns.hasOwnProperty(tableName)) {
          const attributesToSearch = tableColumns[tableName];
          const attributesIntToSearch = columnsInt[tableName] || [];
          const whereCondition = {
            [Op.or]: [
              ...attributesToSearch.map(attribute => ({
                [attribute]: {
                  [Op.iLike] : `%${searchQuery}%`,
                },
              })),
              ...attributesIntToSearch.map(attribute => (
                Sequelize.where(
                  Sequelize.cast(Sequelize.col(`${tableName}.${attribute}`), 'varchar'),
                  { [Op.iLike]: `%${searchQuery}%` }
                )
              )),
            ],
          };

          const hasPermission = await checkPermissions(`READ_${tableName.toUpperCase()}`, currentUser);
          if (!hasPermission) {
            continue;
          }

          const foundRecords = await db[tableName].findAll({
            where: whereCondition,
            attributes: [...tableColumns[tableName], 'id', ...attributesIntToSearch],
          });

          const modifiedRecords = foundRecords.map((record) => {
            const matchAttribute = [];

            for (const attribute of attributesToSearch) {
              if (record[attribute]?.toLowerCase()?.includes(searchQuery.toLowerCase())) {
                matchAttribute.push(attribute);
              }
            }

            for (const attribute of attributesIntToSearch) {
              const castedValue = String(record[attribute]);
              if (castedValue && castedValue.toLowerCase().includes(searchQuery.toLowerCase())) {
                matchAttribute.push(attribute);
              }
            }

            return {
              ...record.get(),
              matchAttribute,
              tableName,
            };
          });

          allFoundRecords = allFoundRecords.concat(modifiedRecords);
        }
      }

      return allFoundRecords;
    } catch (error) {
      throw error;
    }
  }
}
