import { Inject, Injectable } from '@nestjs/common';
import { CheckUpdateQuery } from './check-update.query';
import { AppVersionRepository, APP_VERSION_REPOSITORY } from '@/domain/repositories/app-version.repository';
import { VersionCode } from '@/domain/value-objects/version-code.vo';

export interface UpdateCheckResult {
  hasUpdate: boolean;
  isForceUpdate: boolean;
  latestVersion: {
    versionCode: number;
    versionName: string;
    downloadUrl: string;
    fileSize: string;
    fileSha256: string;
    changelog: string;
    minOsVersion: string | null;
    releaseDate: Date | null;
  } | null;
}

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

  async execute(query: CheckUpdateQuery): Promise<UpdateCheckResult> {
    const latestVersion = await this.appVersionRepository.findLatestByPlatform(query.platform);

    if (!latestVersion) {
      return {
        hasUpdate: false,
        isForceUpdate: false,
        latestVersion: null,
      };
    }

    const currentVersionCode = VersionCode.create(query.currentVersionCode);
    const hasUpdate = latestVersion.isNewerThan(currentVersionCode);

    return {
      hasUpdate,
      isForceUpdate: hasUpdate && latestVersion.shouldForceUpdate(),
      latestVersion: hasUpdate
        ? {
            versionCode: latestVersion.versionCode.value,
            versionName: latestVersion.versionName.value,
            downloadUrl: latestVersion.downloadUrl.value,
            fileSize: latestVersion.fileSize.bytes.toString(),
            fileSha256: latestVersion.fileSha256.value,
            changelog: latestVersion.changelog.value,
            minOsVersion: latestVersion.minOsVersion?.value ?? null,
            releaseDate: latestVersion.releaseDate,
          }
        : null,
    };
  }
}
