import { Inject, Injectable, NotFoundException } from '@nestjs/common'
import { UpdateVersionCommand } from './update-version.command'
import { AppVersionRepository, APP_VERSION_REPOSITORY } from '@/domain/repositories/app-version.repository'
import { AppVersion } from '@/domain/entities/app-version.entity'

@Injectable()
export class UpdateVersionHandler {
  constructor(
    @Inject(APP_VERSION_REPOSITORY)
    private readonly appVersionRepository: AppVersionRepository,
  ) {}

  async execute(command: UpdateVersionCommand): Promise<AppVersion> {
    const version = await this.appVersionRepository.findById(command.id)

    if (!version) {
      throw new NotFoundException(`Version with ID ${command.id} not found`)
    }

    // Apply updates through domain methods
    if (command.isForceUpdate !== undefined) {
      version.setForceUpdate(command.isForceUpdate, command.updatedBy)
    }

    if (command.releaseDate !== undefined) {
      version.setReleaseDate(command.releaseDate, command.updatedBy)
    }

    // For other fields, we need to use the repository update method
    return await this.appVersionRepository.update(command.id, version)
  }
}
