import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Profile } from './entities/profile.entity';
import { CreateProfileDto } from './dto/create-profile.dto';
import { UpdateProfileDto } from './dto/update-profile.dto';

@Injectable()
export class ProfilesService {
  private static readonly MAX_PROFILES_PER_USER = 5;

  constructor(
    @InjectRepository(Profile)
    private readonly profileRepository: Repository<Profile>,
  ) {}

  async create(userId: string, createProfileDto: CreateProfileDto): Promise<Profile> {
    const count = await this.profileRepository.count({ where: { userId } });

    if (count >= ProfilesService.MAX_PROFILES_PER_USER) {
      throw new ForbiddenException(
        `Maximum of ${ProfilesService.MAX_PROFILES_PER_USER} profiles per user`,
      );
    }

    const profile = this.profileRepository.create({
      userId,
      ...createProfileDto,
    });

    return this.profileRepository.save(profile);
  }

  async findAllByUser(userId: string): Promise<Profile[]> {
    return this.profileRepository.find({
      where: { userId },
      order: { name: 'ASC' },
    });
  }

  async findById(id: string, userId: string): Promise<Profile> {
    const profile = await this.profileRepository.findOne({
      where: { id, userId },
    });

    if (!profile) {
      throw new NotFoundException(`Profile with ID "${id}" not found`);
    }

    return profile;
  }

  async update(
    id: string,
    userId: string,
    updateProfileDto: UpdateProfileDto,
  ): Promise<Profile> {
    const profile = await this.findById(id, userId);
    Object.assign(profile, updateProfileDto);
    return this.profileRepository.save(profile);
  }

  async remove(id: string, userId: string): Promise<void> {
    const profile = await this.findById(id, userId);
    await this.profileRepository.remove(profile);
  }
}
