import { Repository } from 'typeorm';

export class ValidationHelper {
  static async validateExistenceInDB(
    repository: Repository<any>,
    fieldName: string,
    value: any,
  ): Promise<boolean> {
    const entity = await repository.findOne({
      where: { [fieldName]: value },
    });
    return !!entity;
  }

  static async validateRequiredFields(
    requiredFields: string[],
    data: any,
  ): Promise<{ success: boolean; missingFields?: string[] }> {
    const missingFields = requiredFields.filter(
      (field) => !data[field] && data[field] !== 0,
    );
    if (missingFields.length) {
      return { success: false, missingFields };
    }
    return { success: true };
  }
  static validateColumns(
    row: any,
    requiredColumns: string[],
    optionalColumns: string[] = [],
  ): {
    success: boolean;
    missingColumns?: string[];
    invalidColumns?: string[];
  } {
    const rowColumns = Object.keys(row);
    const missingColumns = requiredColumns.filter(
      (column) => !rowColumns.includes(column),
    );
    const validColumns = [...requiredColumns, ...optionalColumns];
    const invalidColumns = rowColumns.filter(
      (column) => !validColumns.includes(column),
    );

    if (missingColumns.length || invalidColumns.length) {
      return { success: false, missingColumns, invalidColumns };
    }
    return { success: true };
  }

  static isValidValue<T>(value: T, validValues: T[]): boolean {
    return validValues.includes(value);
  }
  static isValidAccountIdFormat(id: string): boolean {
    return /^(TEMP\d+|R\d{4,6}|R\d+|[A-Za-z0-9]{18})$/.test(id);
  }
  static isValidEmail(email: string): boolean {
    const emails = email.split(',').map((e) => e.trim());
    const emailRegex = /^[a-zA-Z0-9._%+-]*@?[a-zA-Z0-9.-]*\.[a-zA-Z]{2,}$/;
    const isValid = emails.every((e) => emailRegex.test(e));
    return isValid;
  }
  //validate that account name contains at least one non-numeric character:
  static validateAccountName(name: string): boolean {
    // Regular expression to check for at least one non-numeric character
    const regex = /[^\d]/;
    return regex.test(name);
  }
  //validate industry to contain non numeric characters only
  static validateIndustry(industry: string): boolean {
    // Regular expression to check for at least one non-numeric character
    const regex = /^[^0-9]+$/;
    return regex.test(industry);
  }
}
