import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateServiceDto } from './dto/create-service.dto';
import { UpdateServiceDto } from './dto/update-service.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ILike, Repository } from 'typeorm';
import { GetServiceQueryDto } from './dto/get-service-query.dto';
import { Service } from '@/entities/service.entity';
import { join } from 'path';
import { existsSync, unlinkSync } from 'fs';
import { getFileUrl } from '@/common/helpers';
import { folderServiceUpload } from '@/common/constant';

@Injectable()
export class ServiceService {
  constructor(
    @InjectRepository(Service)
    private readonly serviceRepo: Repository<Service>,
  ) {}
  create(createServiceDto: CreateServiceDto, imagePath?: string) {
    const service = this.serviceRepo.create({
      ...createServiceDto,
      image: imagePath,
    });
    return this.serviceRepo.save(service);
  }

  findAll(search?: GetServiceQueryDto) {
    if (search?.keyword) {
      return this.serviceRepo.find({
        where: [
          { name_vi: ILike(`%${search?.keyword}%`) },
          { name_en: ILike(`%${search?.keyword}%`) },
          { name_zh: ILike(`%${search?.keyword}%`) },
        ],
      });
    }
    return this.serviceRepo.find();
  }

  async findOne(id: number) {
    const service = await this.serviceRepo.findOne({ where: { id } });
    if (!service) throw new NotFoundException('Service not found');
    return {
      ...service,
      image: getFileUrl(folderServiceUpload, service.image),
    };
  }

  async update(
    id: number,
    updateServiceDto: UpdateServiceDto,
    imagePath?: string,
  ) {
    const service = await this.findOne(id);
    if (!service) throw new Error('Service not found');

    if (updateServiceDto.image && service.image) {
      const oldImagePath = join(
        process.cwd(),
        'uploads/service',
        service.image,
      );
      if (existsSync(oldImagePath)) {
        unlinkSync(oldImagePath);
      }
    }

    Object.assign(service, updateServiceDto);
    if (imagePath) service.image = imagePath;
    return this.serviceRepo.save(service);
  }

  async remove(id: number) {
    const service = await this.findOne(id);
    if (!service) {
      throw new NotFoundException(`Service not found`);
    }
    return this.serviceRepo.delete(id);
  }
}
