import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Player } from 'src/players/entities/player.entity';
import { Team } from 'src/teams/entities/team.entity';
import { Repository } from 'typeorm';
import { faker } from '@faker-js/faker';
import { User } from 'src/users/entities/user.entity';

@Injectable()
export class PlayersSeedService {
  constructor(
    @InjectRepository(Player)
    private repository: Repository<Player>,
    @InjectRepository(Team)
    private teamRepository: Repository<Team>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async run() {
    const dev = await this.teamRepository.findOne({ where: { id: 1 } });

    const countPlayer = await this.repository.count();

    if (countPlayer === 0) {
      const players = [];
      for (let index = 0; index < 20; index++) {
        const p = this.repository.create({
          firstName: faker.name.firstName(),
          lastName: faker.name.lastName(),
          teamRole: {
            id: 1,
            name: 'player',
          },
          team: dev,
        });
        players.push(p);
      }

      const p2 = this.repository.create({
        firstName: 'Player',
        lastName: 'Kapitän',
        teamRole: {
          id: 3,
          name: 'captain',
        },
        team: dev,
      });

      const u = await this.userRepository.findOne({
        where: { email: 'mail@bastian-wagner.de' },
      });

      const p3 = this.repository.create({
        firstName: 'Player',
        lastName: 'Kassenwart',
        teamRole: {
          id: 4,
          name: 'treasurer',
        },
        team: dev,
        user: u,
      });

      await this.repository.save(players);
      await this.repository.save([p2, p3]);
    }
  }
}
