import { Inject, Injectable } from '@nestjs/common'
import { ListVersionsQuery } from './list-versions.query'
import { AppVersionRepository, APP_VERSION_REPOSITORY } from '@/domain/repositories/app-version.repository'
import { AppVersion } from '@/domain/entities/app-version.entity'
import { Platform } from '@/domain/enums/platform.enum'

@Injectable()
export class ListVersionsHandler {
  constructor(
    @Inject(APP_VERSION_REPOSITORY)
    private readonly appVersionRepository: AppVersionRepository,
  ) {}

  async execute(query: ListVersionsQuery): Promise<AppVersion[]> {
    if (query.platform) {
      return await this.appVersionRepository.findAllByPlatform(query.platform, query.includeDisabled)
    }

    // If no platform specified, get all versions from both platforms
    const androidVersions = await this.appVersionRepository.findAllByPlatform(
      Platform.ANDROID,
      query.includeDisabled,
    )
    const iosVersions = await this.appVersionRepository.findAllByPlatform(Platform.IOS, query.includeDisabled)

    // Combine and sort by createdAt descending
    return [...androidVersions, ...iosVersions].sort(
      (a, b) => b.createdAt.getTime() - a.createdAt.getTime(),
    )
  }
}
