import { Type } from 'class-transformer';
import {
  ArrayMaxSize,
  IsArray,
  IsBoolean,
  IsDate,
  IsInt,
  Min,
  ValidateIf,
  ValidateNested,
} from 'class-validator';
import { TransformDate } from '../../../../../shared/decorators/class-transformer/transform-date.decorator';
import { TransformNumber } from '../../../../../shared/decorators/class-transformer/transform-number.decorator';
import { MinDate } from '../../../../../shared/decorators/class-validator/min-date.decorator';
import { TransformBoolean } from '../../../../../shared/decorators/class-transformer/transform-boolean.decorator';
import { IsOptional } from '../../../../../shared/decorators/class-validator/is-optional.decorator';

export class UpdateMeal_Recipe {
  @TransformNumber()
  @IsInt()
  @Min(1)
  id: number;

  @ValidateIf((object: UpdateMeal_Recipe) => {
    if (!object.delete && object.delete !== true) return true;

    delete object.consumedServings;

    return false;
  })
  @TransformNumber()
  @IsInt()
  @Min(1)
  consumedServings: number;

  @ValidateIf((object: UpdateMeal_Recipe) => {
    if (!object.consumedServings && object.delete !== false) return true;

    delete object.delete;

    return false;
  })
  @TransformBoolean()
  @IsBoolean()
  delete: boolean;
}

export class UpdateMeal_Food {
  @TransformNumber()
  @IsInt()
  @Min(1)
  id: number;

  @ValidateIf((object: UpdateMeal_Food) => {
    if (!object.delete && object.delete !== true) return true;

    delete object.quantity;

    return false;
  })
  @TransformNumber()
  @IsInt()
  @Min(1)
  quantity: number;

  @ValidateIf((object: UpdateMeal_Food) => {
    if (!object.quantity && object.delete !== false) return true;

    delete object.delete;

    return false;
  })
  @TransformBoolean()
  @IsBoolean()
  delete: boolean;
}

export class UpdateMealDto {
  @IsOptional()
  @TransformDate()
  @IsDate()
  @MinDate('1900-01-01')
  date?: Date;

  @IsOptional()
  @TransformNumber()
  @IsInt()
  @Min(1)
  mealTimeId?: number;

  @IsOptional()
  @IsArray()
  @ArrayMaxSize(48)
  @ValidateNested({ each: true })
  @Type(() => UpdateMeal_Food)
  foods?: UpdateMeal_Food[];

  @IsOptional()
  @IsArray()
  @ArrayMaxSize(16)
  @ValidateNested({ each: true })
  @Type(() => UpdateMeal_Recipe)
  recipes?: UpdateMeal_Recipe[];
}
