import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Player } from '../players/entities/player.entity';
import { RoleEnum } from '../roles/roles.enum';
import { User } from '../users/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class TeamAccessService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Player)
    private readonly playerRepository: Repository<Player>,
  ) {}

  async assertMember(userId: number, teamId: number): Promise<void> {
    await this.assertMinimumRole(userId, teamId, 1);
  }

  async assertManager(userId: number, teamId: number): Promise<void> {
    await this.assertMinimumRole(userId, teamId, 3);
  }

  private async assertMinimumRole(
    userId: number,
    teamId: number,
    minimumRole: number,
  ): Promise<void> {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (user?.role?.id === RoleEnum.admin) return;

    const players = await this.playerRepository.find({
      where: { user: { id: userId }, team: { id: teamId } },
    });
    const highestActiveRole = players
      .filter((player) => player.active)
      .reduce(
        (highest, player) => Math.max(highest, player.teamRole?.id ?? 0),
        0,
      );

    if (highestActiveRole < minimumRole) {
      throw new ForbiddenException('Keine Berechtigung für dieses Team.');
    }
  }
}
