import {
  AfterLoad,
  BeforeInsert,
  Column,
  CreateDateColumn,
  Entity,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { EntityHelper } from 'src/utils/entity-helper';
import { Player } from 'src/players/entities/player.entity';
import { TransactionType } from './transaction-type.entity';

@Entity()
export class Transaction extends EntityHelper {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => Player, {
    eager: false,
  })
  player: Player;

  @Column()
  note: string;

  @Column()
  date: string;

  @Column({ type: 'decimal', precision: 10, scale: 2, default: 0 })
  amount: number;

  @ManyToOne(() => TransactionType, {
    eager: true,
  })
  type?: TransactionType | null;

  @CreateDateColumn()
  createdAt: Date;

  @BeforeInsert()
  async setBalance() {
    if (!this.date) {
      this.date = new Date().toISOString();
    }
    let amount = this.amount;
    if (this.type.id > 10 && amount > 0) {
      amount = amount * -1;
    }
    this.player.balance = Number(this.player.balance) + amount;
    if (this.type.id == 0) {
      this.player.team.balance = Number(this.player.team.balance) + amount;
      await this.player.team.save();
    }
    await this.player.save();
  }

  @AfterLoad()
  updateValue() {
    this.amount = Number(this.amount);
  }
}
