import {
  AfterLoad,
  BeforeInsert,
  Column,
  Entity,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { EntityHelper } from 'src/utils/entity-helper';
import { TeamSetting } from 'src/team-settings/entities/team-setting.entity';
import { Player } from 'src/players/entities/player.entity';
import { TeamWalletTransaction } from 'src/team-wallet-transactions/entities/team-wallet-transaction.entity';

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

  @Column()
  name: string;

  @Column({ unique: true })
  alias: string;

  @Column({ default: false })
  publicAccessEnabled: boolean;

  @Column({ length: 64, nullable: true, unique: true, select: false })
  publicAccessToken?: string | null;

  @OneToMany(() => TeamSetting, (setting) => setting.team, {
    eager: true,
  })
  settings: TeamSetting[];

  @OneToMany(() => TeamWalletTransaction, (transaction) => transaction.team, {
    eager: false,
  })
  transactions: TeamWalletTransaction[];

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

  @OneToMany(() => Player, (player) => player.team)
  players: Player[];

  outstanding?: number;

  @BeforeInsert()
  setAlias() {
    if (!this.alias) {
      this.alias = Date.now() + '';
    }
  }

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