import { IsInt, IsNotEmpty, IsPositive } from "class-validator";
import { ChildEntity, Column, Index, ManyToOne } from "typeorm";
import { ResponseDistanceDonation } from '../responses/ResponseDistanceDonation';
import { Donation } from "./Donation";
import type { Runner } from "./Runner";

/**
 * Defines the DistanceDonation entity.
 * For distanceDonations a donor pledges to donate a certain amount for each kilometer ran by a runner.
 */
@ChildEntity()
@Index(['runner'])
export class DistanceDonation extends Donation {
  /**
   * The donation's associated runner.
   * Used as the source of the donation's distance.
   */
  @IsNotEmpty()
  @ManyToOne(() => require("./Runner").Runner, (runner: Runner) => runner.distanceDonations)
  runner!: Runner;

  /**
   * The donation's amount donated per distance.
   * The amount the donor set to be donated per kilometer that the runner ran.
   */
  @Column()
  @IsInt()
  @IsPositive()
  amountPerDistance: number;

  /**
   * The donation's amount in cents (or whatever your currency's smallest unit is.).
   * Get's calculated from the runner's distance ran and the amount donated per kilometer.
   */
  public get amount(): number {
    let calculatedAmount = 0;
    try {
      calculatedAmount = this.amountPerDistance * (this.runner.distance / 1000);
    } catch (error) {
      throw error;
    }
    return calculatedAmount;
  }

  /**
   * Turns this entity into it's response class.
   */
  public toResponse(): ResponseDistanceDonation {
    return new ResponseDistanceDonation(this);
  }
}
