import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AppVersion, Platform } from '../../domain/entities/app-version.entity';

export interface VersionListFilter {
  platform?: Platform;
  includeDisabled?: boolean;
}

@Injectable()
export class AppVersionRepository {
  constructor(
    @InjectRepository(AppVersion)
    private readonly repo: Repository<AppVersion>,
  ) {}

  async findAll(filter?: VersionListFilter): Promise<AppVersion[]> {
    const qb = this.repo.createQueryBuilder('v');

    if (filter?.platform) {
      qb.andWhere('v.platform = :platform', { platform: filter.platform });
    }

    if (!filter?.includeDisabled) {
      qb.andWhere('v.isEnabled = true');
    }

    qb.orderBy('v.createdAt', 'DESC');
    return qb.getMany();
  }

  async findById(id: string): Promise<AppVersion | null> {
    return this.repo.findOne({ where: { id } });
  }

  async create(data: Partial<AppVersion>): Promise<AppVersion> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async update(id: string, data: Partial<AppVersion>): Promise<AppVersion | null> {
    await this.repo.update(id, data);
    return this.findById(id);
  }

  async delete(id: string): Promise<void> {
    await this.repo.delete(id);
  }

  /** 查询指定平台最新启用版本（buildNumber 最大的已启用版本） */
  async findLatestEnabled(platform: Platform): Promise<AppVersion | null> {
    const versions = await this.repo
      .createQueryBuilder('v')
      .where('v.platform = :platform', { platform })
      .andWhere('v.isEnabled = true')
      .orderBy('v.createdAt', 'DESC')
      .getMany();

    if (versions.length === 0) return null;

    // 找 buildNumber（整数）最大的版本，兼容字符串存储
    return versions.reduce((best, cur) => {
      const bestCode = parseInt(best.buildNumber, 10) || 0;
      const curCode = parseInt(cur.buildNumber, 10) || 0;
      return curCode > bestCode ? cur : best;
    });
  }
}
