import { Injectable } from '@nestjs/common'
import { AppVersion as PrismaAppVersion, Platform as PrismaPlatform } from '@prisma/client'
import {
  AppVersion,
  Platform,
  VersionCode,
  VersionName,
  BuildNumber,
  DownloadUrl,
  FileSize,
  FileSha256,
  Changelog,
  MinOsVersion,
} from '../../../domain/version-management'

@Injectable()
export class AppVersionMapper {
  toDomain(prisma: PrismaAppVersion): AppVersion {
    return AppVersion.reconstitute({
      id: prisma.id,
      platform: prisma.platform as Platform,
      versionCode: VersionCode.create(prisma.versionCode),
      versionName: VersionName.create(prisma.versionName),
      buildNumber: BuildNumber.create(prisma.buildNumber),
      downloadUrl: DownloadUrl.create(prisma.downloadUrl),
      fileSize: FileSize.create(prisma.fileSize),
      fileSha256: FileSha256.create(prisma.fileSha256),
      changelog: Changelog.create(prisma.changelog),
      isForceUpdate: prisma.isForceUpdate,
      isEnabled: prisma.isEnabled,
      minOsVersion: prisma.minOsVersion ? MinOsVersion.create(prisma.minOsVersion) : null,
      releaseDate: prisma.releaseDate,
      createdAt: prisma.createdAt,
      updatedAt: prisma.updatedAt,
      createdBy: prisma.createdBy,
      updatedBy: prisma.updatedBy,
    })
  }

  toPersistence(
    domain: AppVersion,
  ): Omit<PrismaAppVersion, 'createdAt' | 'updatedAt'> {
    return {
      id: domain.id,
      platform: domain.platform as PrismaPlatform,
      versionCode: domain.versionCode.value,
      versionName: domain.versionName.value,
      buildNumber: domain.buildNumber.value,
      downloadUrl: domain.downloadUrl.value,
      fileSize: domain.fileSize.bytes,
      fileSha256: domain.fileSha256.value,
      changelog: domain.changelog.value,
      isForceUpdate: domain.isForceUpdate,
      isEnabled: domain.isEnabled,
      minOsVersion: domain.minOsVersion?.value ?? null,
      releaseDate: domain.releaseDate,
      createdBy: domain.createdBy,
      updatedBy: domain.updatedBy,
    }
  }
}
