/*
 * Copyright 2025 Daytona Platforms Inc.
 * SPDX-License-Identifier: AGPL-3.0
 */

import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'
import { SnapshotState } from '../enums/snapshot-state.enum'
import { Snapshot } from '../entities/snapshot.entity'
import { BuildInfoDto } from './build-info.dto'
import { IsOptional } from 'class-validator'

export class SnapshotDto {
  @ApiProperty()
  id: string

  @ApiPropertyOptional()
  organizationId?: string

  @ApiProperty()
  general: boolean

  @ApiProperty()
  name: string

  @ApiPropertyOptional()
  imageName?: string

  @ApiProperty({
    enum: SnapshotState,
    enumName: 'SnapshotState',
  })
  state: SnapshotState

  @ApiProperty({ nullable: true })
  size: number | null

  @ApiProperty({ nullable: true })
  entrypoint: string[] | null

  @ApiProperty()
  cpu: number

  @ApiProperty()
  gpu: number

  @ApiProperty()
  mem: number

  @ApiProperty()
  disk: number

  @ApiProperty({ nullable: true })
  errorReason: string | null

  @ApiProperty()
  createdAt: Date

  @ApiProperty()
  updatedAt: Date

  @ApiProperty({ nullable: true })
  lastUsedAt: Date | null

  @ApiPropertyOptional({
    description: 'Build information for the snapshot',
    type: BuildInfoDto,
  })
  buildInfo?: BuildInfoDto

  @ApiPropertyOptional({
    description: 'IDs of regions where the snapshot is available',
    type: [String],
  })
  regionIds?: string[]

  @ApiPropertyOptional({
    description: 'The initial runner ID of the snapshot',
    example: 'runner123',
    required: false,
  })
  @IsOptional()
  initialRunnerId?: string

  @ApiPropertyOptional({
    description: 'The snapshot reference',
    example: 'daytonaio/sandbox:latest',
    required: false,
  })
  @IsOptional()
  ref?: string

  static fromSnapshot(snapshot: Snapshot): SnapshotDto {
    return {
      id: snapshot.id,
      organizationId: snapshot.organizationId,
      general: snapshot.general,
      name: snapshot.name,
      imageName: snapshot.imageName,
      state: snapshot.state,
      size: snapshot.size ?? null,
      entrypoint: snapshot.entrypoint ?? null,
      cpu: snapshot.cpu,
      gpu: snapshot.gpu,
      mem: snapshot.mem,
      disk: snapshot.disk,
      errorReason: snapshot.errorReason ?? null,
      createdAt: snapshot.createdAt,
      updatedAt: snapshot.updatedAt,
      lastUsedAt: snapshot.lastUsedAt ?? null,
      buildInfo: snapshot.buildInfo
        ? {
            dockerfileContent: snapshot.buildInfo.dockerfileContent,
            contextHashes: snapshot.buildInfo.contextHashes,
            createdAt: snapshot.buildInfo.createdAt,
            updatedAt: snapshot.buildInfo.updatedAt,
            snapshotRef: snapshot.buildInfo.snapshotRef,
          }
        : undefined,
      regionIds: snapshot.snapshotRegions?.map((sr) => sr.regionId) ?? undefined,
      initialRunnerId: snapshot.initialRunnerId,
      ref: snapshot.ref,
    }
  }
}
