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

          
            "organizations": [
              
                "name",
              
            ],
          
        
          
          

          
            "oauth_accounts": [
              
                "provider_user_key",
              
                "access_token",
              
                "refresh_token",
              
            ],
          
        
          
          

          
            "artist_profiles": [
              
                "artist_name",
              
                "legal_name",
              
                "country",
              
                "city",
              
                "tax_residency",
              
                "payout_currency",
              
                "bio",
              
                "website_url",
              
                "vk_url",
              
                "youtube_url",
              
                "tiktok_url",
              
                "instagram_url",
              
            ],
          
        
          
          

          
            "teams": [
              
                "name",
              
                "description",
              
            ],
          
        
          
          

          
        
          
          

          
            "plans": [
              
                "name",
              
                "price_currency",
              
                "billing_period",
              
                "features",
              
            ],
          
        
          
          

          
            "subscriptions": [
              
                "external_billing_key",
              
            ],
          
        
          
          

          
            "distribution_platforms": [
              
                "name",
              
                "website_url",
              
            ],
          
        
          
          

          
            "genres": [
              
                "name",
              
            ],
          
        
          
          

          
            "releases": [
              
                "title",
              
                "language",
              
                "label_name",
              
                "copyright_notice",
              
                "production_notice",
              
                "upc_code",
              
                "moderation_notes",
              
                "internal_catalog_code",
              
            ],
          
        
          
          

          
            "tracks": [
              
                "title",
              
                "version",
              
                "isrc_code",
              
                "lyrics",
              
                "audio_fingerprint",
              
                "quality_notes",
              
            ],
          
        
          
          

          
            "track_contributors": [
              
                "name",
              
                "spotify_artist_url",
              
                "apple_artist_url",
              
                "society_identifier",
              
            ],
          
        
          
          

          
            "release_deliveries": [
              
                "platform_release_url",
              
                "external_reference",
              
                "error_message",
              
            ],
          
        
          
          

          
            "smart_links": [
              
                "slug",
              
                "page_title",
              
                "custom_text",
              
                "theme_color",
              
            ],
          
        
          
          

          
            "smart_link_destinations": [
              
                "destination_url",
              
            ],
          
        
          
          

          
            "smart_link_clicks": [
              
                "country",
              
                "city",
              
                "referrer",
              
                "utm_source",
              
                "utm_campaign",
              
            ],
          
        
          
          

          
            "playlists": [
              
                "name",
              
                "curator_name",
              
                "playlist_url",
              
                "genre_focus",
              
                "mood_tags",
              
            ],
          
        
          
          

          
            "pitch_requests": [
              
                "pitch_title",
              
                "pitch_text",
              
                "mood",
              
                "similar_artists",
              
                "achievements",
              
                "decision_notes",
              
            ],
          
        
          
          

          
            "playlist_placements": [
              
                "notes",
              
            ],
          
        
          
          

          
            "royalty_reports": [
              
                "source_reference",
              
                "error_details",
              
            ],
          
        
          
          

          
            "royalty_lines": [
              
                "territory",
              
                "store_name",
              
                "currency",
              
            ],
          
        
          
          

          
            "wallets": [
              
                "currency",
              
            ],
          
        
          
          

          
            "wallet_transactions": [
              
                "currency",
              
                "description",
              
                "external_reference",
              
            ],
          
        
          
          

          
            "payout_methods": [
              
                "method_label",
              
                "account_identifier",
              
                "holder_name",
              
                "country",
              
            ],
          
        
          
          

          
            "withdrawal_requests": [
              
                "currency",
              
                "processor_reference",
              
                "failure_reason",
              
            ],
          
        
          
          

          
            "tax_documents": [
              
                "notes",
              
            ],
          
        
          
          

          
            "analytics_daily": [
              
                "country",
              
                "city",
              
                "traffic_source",
              
            ],
          
        
          
          

          
            "notifications": [
              
                "title",
              
                "message",
              
                "provider_reference",
              
            ],
          
        
          
          

          
            "notification_preferences": [
              
                "quiet_hours",
              
            ],
          
        
          
          

          
            "api_keys": [
              
                "name",
              
                "key_prefix",
              
                "key_hash",
              
                "scopes",
              
            ],
          
        
          
          

          
            "dashboard_widgets": [
              
                "settings_json",
              
            ],
          
        
          
          

          
            "activity_events": [
              
                "headline",
              
                "details",
              
                "entity_name",
              
                "entity_key",
              
            ],
          
        
          
          

          
            "blog_posts": [
              
                "title",
              
                "slug",
              
                "excerpt",
              
                "content",
              
                "seo_title",
              
                "seo_description",
              
            ],
          
        
          
          

          
            "faq_items": [
              
                "question",
              
                "answer",
              
            ],
          
        
          
          

          
            "contact_messages": [
              
                "name",
              
                "email",
              
                "subject",
              
                "message",
              
            ],
          
        
          
          

          
            "referral_programs": [
              
                "name",
              
            ],
          
        
          
          

          
            "referral_links": [
              
                "code",
              
                "landing_url",
              
            ],
          
        
          
          

          
            "referral_conversions": [
              
                "currency",
              
            ],
          
        
      };
      const columnsInt = {
        
          
          
          
        
          
          
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "plans": [
              
                "price_amount",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "tracks": [
              
                "track_number",
              
                "duration_seconds",
              
                "sample_rate_hz",
              
                "bitrate_kbps",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "smart_link_destinations": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "playlist_placements": [
              
                "position",
              
            ],
          
        
          
          
          
        
          
          
          
            "royalty_lines": [
              
                "quantity",
              
                "unit_rate",
              
                "gross_amount",
              
                "net_amount",
              
            ],
          
        
          
          
          
            "wallets": [
              
                "available_balance",
              
                "pending_balance",
              
                "lifetime_earned",
              
                "lifetime_paid_out",
              
                "minimum_withdrawal_amount",
              
            ],
          
        
          
          
          
            "wallet_transactions": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "withdrawal_requests": [
              
                "amount",
              
            ],
          
        
          
          
          
        
          
          
          
            "analytics_daily": [
              
                "streams",
              
                "unique_listeners",
              
                "saves",
              
                "likes",
              
                "shares",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
        
          
          
          
            "dashboard_widgets": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
        
          
          
          
            "faq_items": [
              
                "sort_order",
              
            ],
          
        
          
          
          
        
          
          
          
            "referral_programs": [
              
                "commission_percent",
              
                "validity_days",
              
            ],
          
        
          
          
          
        
          
          
          
            "referral_conversions": [
              
                "commission_amount",
              
            ],
          
        
      };

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