import { IsBoolean, IsInt, IsOptional, IsPositive } from 'class-validator';
import { getConnection } from 'typeorm';
import { RunnerNotFoundError } from '../../../errors/RunnerErrors';
import { Runner } from '../../entities/Runner';
import { RunnerCard } from '../../entities/RunnerCard';

/**
 * This class is used to update a RunnerCard entity (via put request).
 */
export class UpdateRunnerCard {
    /**
     * The updated card's id.
     * This shouldn't have changed but it is here in case anyone ever wants to enable id changes (whyever they would want to).
     */
    @IsInt()
    @IsPositive()
    id?: number;

    /**
     * The updated card's associated runner's id.
     */
    @IsInt()
    @IsOptional()
    runner?: number;

    /**
     * Is the updated card enabled (for fraud reasons)?
     * Default: true
     */
    @IsBoolean()
    enabled: boolean = true;

    /**
     * Creates a new RunnerCard entity from this.
     */
    public async update(card: RunnerCard): Promise<RunnerCard> {
        card.enabled = this.enabled;
        card.runner = await this.getRunner();

        return card;
    }

    public async getRunner(): Promise<Runner> {
        if (!this.runner) { return null; }
        const runner = await getConnection().getRepository(Runner).findOne({ id: this.runner });
        if (!runner) {
            throw new RunnerNotFoundError();
        }
        return runner;
    }
}