import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AppVersion } from '../../domain/entities/app-version.entity';
import { Platform } from '../../domain/enums/platform.enum';
import { AppType } from '../../domain/enums/app-type.enum';
import { IAppVersionRepository } from '../../domain/repositories/app-version.repository.interface';

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

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

  async findLatestEnabled(appType: AppType, platform: Platform): Promise<AppVersion | null> {
    return this.repo.findOne({
      where: { appType, platform, isEnabled: true },
      order: { versionCode: 'DESC' },
    });
  }

  async findByPlatformAndCode(appType: AppType, platform: Platform, versionCode: number): Promise<AppVersion | null> {
    return this.repo.findOne({
      where: { appType, platform, versionCode },
    });
  }

  async findByFilters(appType?: AppType, platform?: Platform, includeDisabled = false): Promise<AppVersion[]> {
    const where: any = {};
    if (appType) where.appType = appType;
    if (platform) where.platform = platform;
    if (!includeDisabled) where.isEnabled = true;

    return this.repo.find({
      where,
      order: { versionCode: 'DESC' },
    });
  }

  create(data: Partial<AppVersion>): AppVersion {
    return this.repo.create(data);
  }

  async save(entity: AppVersion): Promise<AppVersion> {
    return this.repo.save(entity);
  }

  async updatePartial(id: string, data: Partial<AppVersion>): Promise<void> {
    await this.repo.update(id, data);
  }

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