import { Injectable } from '@nestjs/common';
import { CreatePenaltyDTO } from './dto/create-penalty.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Team } from 'src/teams/entities/team.entity';
import { Repository } from 'typeorm';
import { PenaltyEntity } from './entities/penalty.entity';
import { Player } from 'src/players/entities/player.entity';

@Injectable()
export class PenaltyService {
  constructor(
    @InjectRepository(Team)
    private teamRepository: Repository<Team>,
    @InjectRepository(Player)
    private playerRepository: Repository<Player>,
    @InjectRepository(PenaltyEntity)
    private repository: Repository<PenaltyEntity>,
  ) {}

  async createPenalty(dto: CreatePenaltyDTO, userId: string) {
    const player = await this.playerRepository.findOne({
      where: { user: { id: Number(userId) }, team: { id: dto.teamId } },
      relations: ['team'],
    });

    if (!player || !player.team) {
      return;
    }

    dto.team = player.team;

    const e = this.repository.create(dto);

    return this.repository.save(e);
  }

  getAll(userId: string) {
    const id = Number(userId);

    return this.repository.find({
      where: {
        team: { players: { user: { id } } },
      },
      relations: ['team'],
    });
  }

  async getTeamPenalties(teamId: string | number) {
    teamId = Number(teamId);

    const res = await this.repository.find({
      where: {
        team: { id: teamId },
      },
    });
    return res.map((r) => {
      r.amount = Number(r.amount);
      return r;
    });
  }
}
