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'],

        access_roles: ['name'],

        ai_agents: ['name', 'version'],

        alerts: ['message'],

        automation_jobs: ['workflow_name', 'error_msg'],

        campaigns: ['name'],

        compliance_audits: ['report_url'],

        compliance_issues: ['description'],

        expansion_plans: ['territory'],

        infrastructure_statuses: ['service'],

        market_signals: ['competitor', 'description'],

        patient_messages: ['sender', 'message'],

        patient_profiles: [
          'health_metrics',

          'prescriptions',

          'appointments',

          'billing',
        ],

        platform_metrics: ['region'],

        pricing_strategies: ['name', 'product', 'metrics'],

        revenue_summaries: ['month', 'payer_breakdown'],

        subscriber_activities: ['action', 'object'],

        subscriber_roles: ['role_name'],

        subscribers: ['name', 'org', 'email'],

        support_tickets: ['subject'],

        organizations: ['name'],
      };
      const columnsInt = {
        access_roles: ['user_count'],

        ai_agents: ['accuracy_pct', 'latency_ms'],

        automation_jobs: ['runtime_ms'],

        campaigns: [
          'spend',

          'impressions',

          'clicks',

          'conversions',

          'cpa',

          'ctr_pct',
        ],

        compliance_audits: ['issues_found'],

        expansion_plans: ['projected_roi_pct'],

        infrastructure_statuses: ['uptime_pct', 'latency_ms', 'error_rate'],

        invoices: ['amount'],

        market_signals: ['impact_score'],

        platform_metrics: ['api_latency_ms', 'uptime_pct', 'page_load_ms'],

        pricing_strategies: ['price'],

        revenue_summaries: ['total_amount', 'growth_pct'],
      };

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