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 , organizationId, globalAccess) {
    try {
      if (!searchQuery) {
        throw new ValidationError('iam.errors.searchQueryRequired');
      }
      const tableColumns = {
        
          
          

          
            "users": [
              
                "firstName",
              
                "lastName",
              
                "phoneNumber",
              
                "email",
              
            ],
          
        
          
          
          
          

          
            "companies": [
              
                "name",
              
            ],
          
        
          
          

          
            "drivers": [
              
                "driver_code",
              
                "driver_name",
              
                "phone",
              
                "email",
              
                "address",
              
                "license_number",
              
                "national_id",
              
                "trn_tax_id",
              
                "notes",
              
            ],
          
        
          
          

          
            "vehicles": [
              
                "vehicle_code",
              
                "plate_no",
              
                "engine_no",
              
                "chassis_no",
              
                "make",
              
                "model",
              
                "colour",
              
                "category",
              
                "branch",
              
                "insurance_policy_no",
              
                "notes",
              
            ],
          
        
          
          

          
            "agreements": [
              
                "agreement_number",
              
                "notes",
              
            ],
          
        
          
          

          
        
          
          

          
            "invoices": [
              
                "invoice_no",
              
            ],
          
        
          
          

          
            "chart_of_accounts": [
              
                "account_code",
              
                "account_name",
              
                "category",
              
            ],
          
        
          
          

          
            "invoice_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "payments": [
              
                "payment_ref",
              
                "reference_no",
              
                "notes",
              
            ],
          
        
          
          

          
            "payment_allocations": [
              
                "notes",
              
            ],
          
        
          
          

          
            "vendors": [
              
                "vendor_code",
              
                "vendor_name",
              
                "phone",
              
                "email",
              
                "address",
              
                "tax_id",
              
                "payment_terms",
              
            ],
          
        
          
          

          
            "vehicle_expenses": [
              
                "expense_no",
              
                "expense_category",
              
                "description",
              
            ],
          
        
          
          

          
            "driver_expenses": [
              
                "expense_category",
              
                "description",
              
            ],
          
        
          
          

          
            "bills": [
              
                "bill_no",
              
            ],
          
        
          
          

          
            "bill_lines": [
              
                "description",
              
            ],
          
        
          
          

          
            "bill_payments": [
              
                "reference_no",
              
            ],
          
        
          
          

          
            "ledger_entries": [
              
                "entry_no",
              
                "source_ref",
              
                "description",
              
            ],
          
        
          
          

          
            "loan_schedules": [
              
                "bank_name",
              
                "payment_no",
              
            ],
          
        
          
          

          
            "vehicle_compliance": [
              
                "insurance_policy_no",
              
                "certificate_no",
              
            ],
          
        
          
          

          
            "documents": [
              
                "entity_ref",
              
                "file_name",
              
                "file_url",
              
            ],
          
        
          
          

          
            "audit_logs": [
              
                "module",
              
                "record_ref",
              
                "old_value",
              
                "new_value",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
            "drivers": [
              
                "security_deposit",
              
                "credit_limit",
              
            ],
          
        
          
          
          
            "vehicles": [
              
                "year",
              
                "purchase_cost",
              
                "odometer",
              
            ],
          
        
          
          
          
            "agreements": [
              
                "daily_rate",
              
                "weekly_rate",
              
                "monthly_rate",
              
                "deposit_amount",
              
            ],
          
        
          
          
          
            "recurring_invoice_templates": [
              
                "rate",
              
            ],
          
        
          
          
          
            "invoices": [
              
                "billing_days",
              
                "holiday_days",
              
                "billable_days",
              
                "daily_rate",
              
                "gross_amount",
              
                "expense_deductions",
              
                "net_amount",
              
                "amount_paid",
              
                "balance_due",
              
            ],
          
        
          
          
          
        
          
          
          
            "invoice_lines": [
              
                "quantity",
              
                "rate",
              
                "amount",
              
            ],
          
        
          
          
          
            "payments": [
              
                "amount",
              
                "allocated_amount",
              
                "unallocated_amount",
              
            ],
          
        
          
          
          
            "payment_allocations": [
              
                "amount_allocated",
              
            ],
          
        
          
          
          
        
          
          
          
            "vehicle_expenses": [
              
                "amount",
              
                "tax_amount",
              
                "gross_amount",
              
            ],
          
        
          
          
          
            "driver_expenses": [
              
                "amount",
              
            ],
          
        
          
          
          
            "bills": [
              
                "gross_amount",
              
                "amount_paid",
              
                "balance_due",
              
            ],
          
        
          
          
          
            "bill_lines": [
              
                "amount",
              
            ],
          
        
          
          
          
            "bill_payments": [
              
                "amount",
              
            ],
          
        
          
          
          
            "ledger_entries": [
              
                "debit",
              
                "credit",
              
            ],
          
        
          
          
          
            "loan_schedules": [
              
                "payment_amount",
              
                "principal",
              
                "interest",
              
                "remaining_balance",
              
            ],
          
        
          
          
          
            "vehicle_compliance": [
              
                "mileage",
              
            ],
          
        
          
          
          
        
          
          
          
        
      };

      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}%` }
                )
              )),
            ],
          };

           
          if (!globalAccess && tableName !== 'organizations' && organizationId) {
            whereCondition.organizationId = organizationId;
          }
          

          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;
    }
  }
}