import { UserViewModel } from '../users/user.presenter.model';
import { User } from '@app/domain/users/user.model';
import { environment } from '@env/environment';

export class UserPresenter {
  private DEFAULT_VALUE = 'Non renséigné';
  toViewModel(user: User): UserViewModel {
    const slug = user.name
      ? this.generateProfileSlug(user.name, user.id)
      : this.generateProfileSlug(this.DEFAULT_VALUE);

    const avatar = user.avatar
      ? `${environment.baseUrl}/api/files/users/${user.id}/${user.avatar}?thumb=320x240`
      : `https://api.dicebear.com/9.x/initials/svg?seed=${user.name ? user.name : user.username ? user.username : this.DEFAULT_VALUE}`;

    let userViewModel: UserViewModel = {
      id: user.id,
      username: user.username ?? this.DEFAULT_VALUE,
      verified: user.verified,
      emailVisibility: user.emailVisibility,
      email: user.email,
      name: user.name ? user.name : this.DEFAULT_VALUE,
      avatar,
      slug,
      isUserVisible: this.isUserVisible(user),
      missingFields: this.missingFields(user),
    };

    if (user.name) {
      const firstName = user.name.split(' ').slice(0, -1).join(' ').toLowerCase().trim() ?? '';
      const lastName = user.name.split(' ').slice(-1)[0].toUpperCase().trim() ?? '';
      userViewModel = { ...userViewModel, firstName, lastName };
    }

    return userViewModel;
  }

  toViewModels(users: User[]): UserViewModel[] {
    return users.map((user) => this.toViewModel(user));
  }

  private generateProfileSlug(name: string, id?: string): string {
    return name
      .concat(id ? ` ${id}` : '')
      .toLowerCase()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '') // Enlève les accents
      .trim()
      .replace(/[^a-z0-9 -]/g, '') // Enlève les caractères spéciaux
      .replace(/\s+/g, '-') // Remplace les espaces par des tirets
      .replace(/-+/g, '-'); // Évite les tirets multiples
  }

  private isUserVisible(currentUser: User) {
    return !!currentUser.name;
  }

  private missingFields(currentUser: User) {
    const missing: string[] = [];

    if (!currentUser?.name) {
      missing.push('nom');
    }

    return missing;
  }
}
