import { Injectable, inject } from '@angular/core';
import { User } from '../../../../shared-kernel';
import {
  EditableProfileAvatarSource,
  ProcessedProfileAvatar,
  ProfileAvatarTransform,
  ProfileAvatarUpdates
} from '../../domain/profile-avatar.models';
import { ProfileAvatarImageService } from '../../infrastructure/services/profile-avatar-image.service';
import { ProfileAvatarStorageService } from '../../infrastructure/services/profile-avatar-storage.service';

@Injectable({ providedIn: 'root' })
export class ProfileAvatarFacade {
  private readonly image = inject(ProfileAvatarImageService);
  private readonly storage = inject(ProfileAvatarStorageService);

  validateFile(file: File): string | null {
    return this.image.validateFile(file);
  }

  prepareEditableSource(file: File): Promise<EditableProfileAvatarSource> {
    return this.image.prepareEditableSource(file);
  }

  releaseEditableSource(source: EditableProfileAvatarSource | null | undefined): void {
    this.image.releaseEditableSource(source);
  }

  processEditableSource(
    source: EditableProfileAvatarSource,
    transform: ProfileAvatarTransform
  ): Promise<ProcessedProfileAvatar> {
    return this.image.processEditableSource(source, transform);
  }

  persistProcessedAvatar(
    user: Pick<User, 'id' | 'username' | 'displayName'>,
    avatar: ProcessedProfileAvatar
  ): Promise<void> {
    return this.storage.persistProcessedAvatar(user, avatar);
  }

  persistAvatarDataUrl(
    user: Pick<User, 'id' | 'username' | 'displayName'>,
    avatarUrl: string | null | undefined
  ): Promise<void> {
    const mimeMatch = avatarUrl?.match(/^data:([^;]+);base64,/i);
    const base64 = avatarUrl?.split(',', 2)[1] ?? '';
    const avatarMime = mimeMatch?.[1]?.toLowerCase() ?? 'image/webp';

    if (!base64) {
      return Promise.resolve();
    }

    return this.storage.persistProcessedAvatar(user, {
      base64,
      avatarMime
    });
  }

  buildAvatarUpdates(avatar: ProcessedProfileAvatar): ProfileAvatarUpdates {
    return {
      avatarUrl: avatar.avatarUrl,
      avatarHash: avatar.avatarHash,
      avatarMime: avatar.avatarMime,
      avatarUpdatedAt: avatar.avatarUpdatedAt
    };
  }
}
