import { ProfileViewModel, ProfileViewModelPaginated } from '../profiles/profile.presenter.model';
import { Profile, ProfilePaginated } from '@app/domain/profiles/profile.model';
import { SettingsProfileDto } from '@app/domain/profiles/dto/settings-profile.dto';
import { User } from '@app/domain/users/user.model';
import { environment } from '@env/environment';
import { UserPresenter } from '../users/user.presenter';

export class ProfilePresenter {
  private readonly userPresenter = new UserPresenter();
  private DEFAULT_BIO = `Je suis sur la plateforme Trouve Ton Profil pour partager mon expertise et mes compétences. N'hésitez pas à me contacter pour en savoir plus sur mon parcours et mes domaines d'intervention.`;

  toViewModelPaginated(profilePaginated: ProfilePaginated): ProfileViewModelPaginated {
    return { ...profilePaginated, items: this.toViewModels(profilePaginated.items) };
  }

  toViewModel(profile: Profile): ProfileViewModel {
    const isProfileVisible = this.isProfileVisible(profile);
    const missingFields = this.missingFields(profile);
    const settings: SettingsProfileDto = {
      showEmail: profile.partageMail ?? false,
      showPhone: profile.partagePhone ?? false,
      allowGeolocation: profile.estGeolocaliser ?? false,
      isProfilePublic: profile.estVisible ?? false,
    };

    const bio = profile.bio ? profile.bio : this.DEFAULT_BIO;

    let profileViewModel: ProfileViewModel = {
      id: profile.id,
      fullName: '', // ❗ exemple volontaire
      isVerifiedLabel: profile.estVerifier ? '✅ Vérifié' : '❌ Non vérifié',
      createdAtFormatted: new Date(profile.created).toLocaleDateString(),
      avatarUrl: ``,
      estVerifier: profile.estVerifier,
      utilisateur: profile.utilisateur,
      profession: profile.profession.toUpperCase() ?? 'Profession non renseignée'.toUpperCase(),
      secteur: profile.secteur,
      reseaux: profile.reseaux,
      apropos: profile.apropos,
      projets: profile.projets,
      cv: profile.cv ? `${environment.baseUrl}/api/files/profiles/${profile.id}/${profile.cv}` : '',
      bio,
      coordonnees: profile.coordonnees
        ? { latitude: profile!.coordonnees!.lat!, longitude: profile!.coordonnees!.lon! }
        : undefined,
      settings,
      isProfileVisible,
      missingFields,
    };

    const profileExpand = (profile as any) ? (profile as any).expand : { utilisateur: {} as User };
    const userExpand = profileExpand ? (profileExpand.utilisateur as User) : undefined;
    if (userExpand !== undefined) {
      const userViewModel = this.userPresenter.toViewModel(userExpand);

      const userSlug = userViewModel.slug ?? '';
      const profileId = profile.id ? profile.id : '';
      const slug = userSlug === '' ? profileId : userSlug.concat('-', profileId);
      const avatarUrl = userExpand.avatar
        ? `${environment.baseUrl}/api/files/users/${profile.utilisateur}/${userExpand.avatar}?thumb=320x240`
        : `https://api.dicebear.com/9.x/initials/svg?seed=${userExpand.name}}`;

      profileViewModel = {
        ...profileViewModel,
        userViewModel,
        slug,
        fullName: userExpand.name,
        avatarUrl,
      };
    }

    return profileViewModel;
  }

  toViewModels(profiles: Profile[]): ProfileViewModel[] {
    return profiles.map((profile) => this.toViewModel(profile));
  }

  private isProfileVisible(currentProfile: Profile) {
    if (!currentProfile) {
      return false;
    }

    const hasProfession = currentProfile.profession
      ? currentProfile.profession.toLowerCase() !== 'profession non renseignée'
      : false;
    const hasSector = !!currentProfile.secteur;

    return hasProfession && hasSector;
  }

  private missingFields(currentProfile: Profile) {
    const missing: string[] = [];

    if (
      !currentProfile?.profession ||
      currentProfile.profession.toLowerCase() === 'profession non renseignée'
    ) {
      missing.push('profession');
    }
    if (!currentProfile?.secteur) {
      missing.push("secteur d'activité");
    }

    return missing;
  }
}
