import { Controller, Get, Query } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'
import { VersionService } from '../../application/services/version.service'
import { Platform } from '../../domain/version-management'
import { CheckUpdateDto } from '../dto/version'
import { Public } from '../../shared/guards/admin-auth.guard'
import { SkipTransform } from '../../shared/interceptors/transform.interceptor'

/**
 * Mobile App Version API Controller
 * Response format matches mining-app (Flutter) expected format:
 * { hasUpdate: boolean, latestVersion?: { versionCode, versionName, ... } }
 */
@ApiTags('Mobile App Version')
@Controller('api/app/version')
export class MobileVersionController {
  constructor(private readonly versionService: VersionService) {}

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

  @Get('check')
  @Public()
  @SkipTransform()
  @ApiOperation({ summary: '检查更新 (mining-app 专用)' })
  async checkUpdate(@Query() dto: CheckUpdateDto) {
    const platform = this.getPlatform(dto.platform)
    const result = await this.versionService.checkUpdate(platform, dto.versionCode)

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

    const v = result.latestVersion
    return {
      hasUpdate: true,
      latestVersion: {
        versionCode: v.versionCode,
        versionName: v.versionName,
        buildNumber: v.buildNumber,
        downloadUrl: v.downloadUrl,
        fileSize: Number(BigInt(v.fileSize)),
        fileSha256: v.fileSha256,
        changelog: v.changelog,
        isForceUpdate: result.isForceUpdate,
        minOsVersion: v.minOsVersion ?? null,
        releaseDate: v.releaseDate?.toISOString() ?? null,
      },
    }
  }
}
