import { Controller, Get, Query } from '@nestjs/common';
import { AppVersionRepository } from '../../../infrastructure/repositories/app-version.repository';
import { Platform } from '../../../domain/entities/app-version.entity';

/**
 * 公开接口：供 IT0 App 检查是否有新版本
 * GET /api/app/version/check
 *
 * 查询参数:
 *   platform           - 平台 (android | ios)，不区分大小写
 *   current_version_code - 当前安装的构建号 (build number)
 *
 * 响应格式（与 Flutter VersionInfo.fromJson 完全对应）:
 *   needUpdate    bool    - 是否需要更新
 *   version       string  - 最新版本号 (versionName, e.g. "1.0.0")
 *   versionCode   int     - 最新构建号 (buildNumber as int)
 *   downloadUrl   string  - APK 下载地址
 *   fileSize      int     - 文件大小（字节）
 *   fileSizeFriendly string - 友好显示 (e.g. "146.9 MB")
 *   sha256        string  - SHA-256（暂未存储，返回空串）
 *   forceUpdate   bool    - 是否强制更新
 *   updateLog     string? - 更新日志
 *   releaseDate   string  - 发布时间 ISO 字符串
 */
@Controller('api/app/version')
export class AppVersionCheckController {
  constructor(private readonly versionRepo: AppVersionRepository) {}

  @Get('check')
  async check(
    @Query('platform') platform: string,
    @Query('current_version_code') currentVersionCode?: string,
  ) {
    const platformEnum = ((platform || 'android').toUpperCase()) as Platform;
    const latest = await this.versionRepo.findLatestEnabled(platformEnum);

    if (!latest) {
      return { needUpdate: false };
    }

    const latestCode = parseInt(latest.buildNumber, 10) || 0;
    const currentCode = parseInt(currentVersionCode || '0', 10) || 0;

    if (latestCode <= currentCode) {
      return { needUpdate: false };
    }

    const fileSizeNum = Number(latest.fileSize) || 0;

    return {
      needUpdate: true,
      version: latest.versionName,
      versionCode: latestCode,
      downloadUrl: latest.downloadUrl || '',
      fileSize: fileSizeNum,
      fileSizeFriendly: formatFileSize(fileSizeNum),
      sha256: '',          // version-service 不存储 sha256，留空
      forceUpdate: latest.isForceUpdate,
      updateLog: latest.changelog ?? null,
      releaseDate: (latest.releaseDate ?? latest.createdAt).toISOString(),
    };
  }
}

function formatFileSize(bytes: number): string {
  if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
  if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${bytes} B`;
}
