import { Controller, Get, Param, Query, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { Response } from 'express';
import { AppVersionService } from '../../../application/services/app-version.service';
import { FileStorageService } from '../../../application/services/file-storage.service';
import { Platform } from '../../../domain/enums/platform.enum';

@ApiTags('app-version')
@Controller('app/version')
export class AppVersionController {
  constructor(
    private readonly versionService: AppVersionService,
    private readonly fileStorage: FileStorageService,
  ) {}

  @Get('check')
  @ApiOperation({ summary: 'Check for app update (mobile client)' })
  @ApiQuery({ name: 'platform', enum: ['android', 'ios', 'ANDROID', 'IOS'] })
  @ApiQuery({ name: 'current_version_code', type: Number })
  async checkUpdate(
    @Query('platform') platform: string,
    @Query('current_version_code') currentVersionCode: string,
  ) {
    const platformEnum = platform.toUpperCase() as Platform;
    const result = await this.versionService.checkUpdate(
      platformEnum,
      parseInt(currentVersionCode, 10),
    );
    return { code: 0, data: result };
  }

  @Get('download/:id')
  @ApiOperation({ summary: 'Download app package' })
  async downloadVersion(@Param('id') id: string, @Res() res: Response) {
    const version = await this.versionService.getVersion(id);
    // Redirect to the download URL (presigned MinIO URL or external URL)
    return res.redirect(302, version.downloadUrl);
  }
}
