import { Inject, Injectable, ConflictException } from '@nestjs/common';
import { CreateVersionCommand } from './create-version.command';
import { AppVersionRepository, APP_VERSION_REPOSITORY } from '@/domain/repositories/app-version.repository';
import { AppVersion } from '@/domain/entities/app-version.entity';
import { VersionCode } from '@/domain/value-objects/version-code.vo';
import { VersionName } from '@/domain/value-objects/version-name.vo';
import { BuildNumber } from '@/domain/value-objects/build-number.vo';
import { DownloadUrl } from '@/domain/value-objects/download-url.vo';
import { FileSize } from '@/domain/value-objects/file-size.vo';
import { FileSha256 } from '@/domain/value-objects/file-sha256.vo';
import { Changelog } from '@/domain/value-objects/changelog.vo';
import { MinOsVersion } from '@/domain/value-objects/min-os-version.vo';

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

  async execute(command: CreateVersionCommand): Promise<AppVersion> {
    // 创建值对象
    const versionCode = VersionCode.create(command.versionCode);
    const versionName = VersionName.create(command.versionName);
    const buildNumber = BuildNumber.create(command.buildNumber);
    const downloadUrl = DownloadUrl.create(command.downloadUrl);
    const fileSize = FileSize.create(command.fileSize);
    const fileSha256 = FileSha256.create(command.fileSha256);
    const changelog = Changelog.create(command.changelog);
    const minOsVersion = command.minOsVersion ? MinOsVersion.create(command.minOsVersion) : null;

    // Check if version already exists
    const existing = await this.appVersionRepository.findByPlatformAndVersionCode(
      command.platform,
      versionCode,
    );

    if (existing) {
      throw new ConflictException(
        `Version ${command.versionCode} already exists for platform ${command.platform}`,
      );
    }

    // 创建领域对象
    const appVersion = AppVersion.create({
      platform: command.platform,
      versionCode,
      versionName,
      buildNumber,
      downloadUrl,
      fileSize,
      fileSha256,
      changelog,
      isForceUpdate: command.isForceUpdate,
      minOsVersion,
      releaseDate: command.releaseDate,
      createdBy: command.createdBy,
    });

    return await this.appVersionRepository.save(appVersion);
  }
}
