import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { LoggingService } from 'src/database/logging/logging.service';
import { RoleEnum } from 'src/roles/roles.enum';
import { TeamRolesEnum } from 'src/team-roles/team-roles.enum';
import { TeamAccessService } from 'src/teams/team-access.service';
import { Team } from 'src/teams/entities/team.entity';
import { User } from 'src/users/entities/user.entity';
import { Repository } from 'typeorm';
import { CreateTeamWalletTransactionDto } from './dto/create-team-wallet-transaction.dto';
import { TeamWalletTransactionType } from './entities/team-wallet-transaction-type.entity';
import { TeamWalletTransaction } from './entities/team-wallet-transaction.entity';
import { TeamWalletTransactionEnum } from './team-wallet-transaction.enum';

@Injectable()
export class TeamWalletTransactionsService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    @InjectRepository(TeamWalletTransaction)
    private teamWalletTransactionRepository: Repository<TeamWalletTransaction>,
    @InjectRepository(TeamWalletTransactionType)
    private teamWalletTransactionTypeRepository: Repository<TeamWalletTransactionType>,
    @InjectRepository(Team)
    private teamRepository: Repository<Team>,
    private logger: LoggingService,
    private access: TeamAccessService,
  ) {}

  async create(data: CreateTeamWalletTransactionDto, userId: string) {
    const creatingUser = await this.usersRepository.findOne({
      where: {
        id: Number(userId),
      },
    });

    if (creatingUser.role.id != RoleEnum.admin) {
      await this.access.assertAtLeast(
        Number(userId),
        data.teamId,
        'transaction_create_min_role',
        TeamRolesEnum.scnd_treasurer,
      );
    }

    const team = await this.teamRepository.findOneByOrFail({
      id: data.teamId,
    });

    const transactionType =
      await this.teamWalletTransactionTypeRepository.findOne({
        where: {
          id: TeamWalletTransactionEnum[TeamWalletTransactionEnum[data.type]],
        },
      });

    // darf es anlegen
    const transaction = await this.teamWalletTransactionRepository.save(
      this.teamWalletTransactionRepository.create({
        amount: data.amount,
        team: team,
        date: data.date,
        type: transactionType,
      }),
    );

    await this.logger.info({
      event: 'team_transaction_create',
      details: `Teambuchung ${transaction.id} angelegt`,
      userId: Number(userId),
    });

    return transaction;
  }
}
