import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { IsBoolean, IsIn, IsOptional, IsString } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { PrismaService } from '../../common/prisma.service';

export class AppReleaseDto {
  @ApiProperty({ enum: ['android', 'ios'] })
  @IsIn(['android', 'ios'])
  os: string;

  @ApiProperty({ example: '1.2.3' })
  @IsString()
  version: string;

  @ApiProperty({ default: false })
  @IsBoolean()
  forceUpdate: boolean;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  storeLink?: string;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString()
  notes?: string;
}

@Injectable()
export class AppReleasesService {
  constructor(private prisma: PrismaService) {}

  private get db() {
    return (this.prisma as any);
  }

  getAll() {
    return this.db.appRelease.findMany({ orderBy: [{ os: 'asc' }, { createdAt: 'desc' }] });
  }

  async getLatest(os: string) {
    const release = await this.db.appRelease.findFirst({
      where: { os },
      orderBy: { createdAt: 'desc' },
    });
    if (!release) throw new NotFoundException(`No release found for ${os}`);
    return release;
  }

  async create(dto: AppReleaseDto) {
    const existing = await this.db.appRelease.findUnique({
      where: { os_version: { os: dto.os, version: dto.version } },
    });
    if (existing) throw new ConflictException(`Release ${dto.os} ${dto.version} already exists`);
    return this.db.appRelease.create({ data: dto });
  }

  async update(id: string, dto: Partial<AppReleaseDto>) {
    const release = await this.db.appRelease.findUnique({ where: { id } });
    if (!release) throw new NotFoundException('App release not found');
    return this.db.appRelease.update({ where: { id }, data: dto });
  }

  async remove(id: string) {
    const release = await this.db.appRelease.findUnique({ where: { id } });
    if (!release) throw new NotFoundException('App release not found');
    await this.db.appRelease.delete({ where: { id } });
    return { deleted: true, id };
  }
}
