import { Controller, Get, Query } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'
import { MobileCheckUpdateDto } from '../dto/request/mobile-check-update.dto'
import { MobileUpdateCheckResultDto } from '../dto/response/version.dto'
import { CheckUpdateHandler } from '@/application/queries/check-update/check-update.handler'
import { CheckUpdateQuery } from '@/application/queries/check-update/check-update.query'
import { Platform } from '@/domain/enums/platform.enum'

/**
 * Mobile App Version API Controller
 * This endpoint is designed to match the mobile app's expected API format
 */
@ApiTags('Mobile App Version')
@Controller('api/app/version')
export class MobileVersionController {
  constructor(private readonly checkUpdateHandler: CheckUpdateHandler) {}

  /**
   * Format file size to human-readable string
   */
  private formatFileSize(bytes: bigint): string {
    const bytesNum = Number(bytes)
    if (bytesNum < 1024) return `${bytesNum} B`
    if (bytesNum < 1024 * 1024) return `${(bytesNum / 1024).toFixed(1)} KB`
    if (bytesNum < 1024 * 1024 * 1024) return `${(bytesNum / (1024 * 1024)).toFixed(1)} MB`
    return `${(bytesNum / (1024 * 1024 * 1024)).toFixed(2)} GB`
  }

  /**
   * Convert platform string to enum
   */
  private getPlatform(platform: string): Platform {
    const normalized = platform.toLowerCase()
    if (normalized === 'ios') return Platform.IOS
    return Platform.ANDROID
  }

  @Get('check')
  @ApiOperation({ summary: '检查更新 (移动端专用)' })
  @ApiResponse({ status: 200, type: MobileUpdateCheckResultDto })
  async checkUpdate(@Query() dto: MobileCheckUpdateDto): Promise<MobileUpdateCheckResultDto> {
    const platform = this.getPlatform(dto.platform)
    const query = new CheckUpdateQuery(platform, dto.current_version_code)
    const result = await this.checkUpdateHandler.execute(query)

    if (!result.hasUpdate || !result.latestVersion) {
      return {
        needUpdate: false,
      }
    }

    const fileSize = BigInt(result.latestVersion.fileSize)

    return {
      needUpdate: true,
      version: result.latestVersion.versionName,
      versionCode: result.latestVersion.versionCode,
      downloadUrl: result.latestVersion.downloadUrl,
      fileSize: Number(fileSize),
      fileSizeFriendly: this.formatFileSize(fileSize),
      sha256: result.latestVersion.fileSha256,
      forceUpdate: result.isForceUpdate,
      updateLog: result.latestVersion.changelog,
      releaseDate: result.latestVersion.releaseDate?.toISOString() ?? new Date().toISOString(),
    }
  }
}
