import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import {
  SearchParams,
  SearchResult,
  SearchResultInfo,
} from '@csr/common/entities'
import { WeightClass } from '../entities/weight.class'

import { WeightClassDto } from '../dtos/weight.class.dto'

@Injectable()
export class WeightClassService {
  constructor(
    @InjectRepository(WeightClass)
    private readonly weightClassRepository: Repository<WeightClass>,
  ) {}

  async search(params: SearchParams): Promise<SearchResult<WeightClass>> {
    const where = {}
    const [data, count] = await this.weightClassRepository.findAndCount({
      where,
      take: params.limit,
      skip: params.getSkip(),
    })

    const info = new SearchResultInfo({
      page: params.page,
      pages: Math.ceil(count / params.limit),
      pageSize: params.limit,
      count,
    })
    return new SearchResult<WeightClass>(data, info)
  }

  async get(id: number): Promise<WeightClass> {
    return this.weightClassRepository.findOne({
      where: {
        id: id,
      },
    })
  }

  async create(weightClassDto: WeightClassDto): Promise<WeightClass> {
    const weightClass = new WeightClass()
    this.fill(weightClass, weightClassDto)

    return this.weightClassRepository.save(weightClass)
  }

  async update(
    id: number,
    weightClassDto: WeightClassDto,
  ): Promise<WeightClass> {
    const weightClass = await this.weightClassRepository.findOneBy({ id: id })
    this.fill(weightClass, weightClassDto)

    return this.weightClassRepository.save(weightClass)
  }

  async delete(id: number): Promise<void> {
    await this.weightClassRepository.delete(id)
  }

  async save(weightClass: WeightClass): Promise<WeightClass> {
    return this.weightClassRepository.save(weightClass)
  }

  async fill(
    weightClass: WeightClass,
    weightClassDto: WeightClassDto,
  ): Promise<void> {
    weightClass.name = weightClassDto.name
    weightClass.code = weightClassDto.code
    weightClass.value = weightClassDto.value
    weightClass.isDefault = weightClassDto.isDefault
    weightClass.isActive = weightClassDto.isActive
  }
}
