import {
  BeforeInsert,
  Column,
  CreateDateColumn,
  Entity,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { EntityHelper } from 'src/utils/entity-helper';
import { TeamWalletTransactionType } from './team-wallet-transaction-type.entity';
import { Team } from 'src/teams/entities/team.entity';

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

  @ManyToOne(() => Team, {
    eager: false,
  })
  team: Team;

  @Column({ default: '' })
  note: string;

  @Column()
  date: string;

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

  @ManyToOne(() => TeamWalletTransactionType, {
    eager: true,
  })
  type?: TeamWalletTransactionType | 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.team.balance = Number(this.team.balance) + amount;
    await this.team.save();
  }
}
