import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Repository } from 'typeorm';
import { ServiceEntity } from './entities/service.entity.js';

@Injectable()
export class ServicesService {
  constructor(
    @InjectRepository(ServiceEntity)
    private servicesRepo: Repository<ServiceEntity>,
  ) {}

  async create(data: Partial<ServiceEntity>) {
    const service = this.servicesRepo.create(data);
    return this.servicesRepo.save(service);
  }

  async findAll() {
    return this.servicesRepo.find({
      where: { parentId: IsNull() },
      relations: { children: true },
      select: {
        id: true,
        name: true,
        slug: true,
        badge: true,
        thumbnailUrl: true,
        description: true,
        footerText: true,
      },
    });
  }

  async findOneBySlug(slug: string) {
    const service = await this.servicesRepo.findOne({
      where: { slug },
      relations: {
        children: true,
      },
    });
    if (!service) throw new NotFoundException('Service not found');
    return service;
  }

  async update(id: number, data: Partial<ServiceEntity>) {
    await this.servicesRepo.update(id, data);
  }

  async remove(id: number) {
    return this.servicesRepo.delete(id);
  }
}
