import { Injectable, InternalServerErrorException, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationHelper } from '../common/helpers/pagination.helper';
import { PaginationQueryDto } from '../common/dto/pagination-query.dto';
import { Create{{pascalCase name}}Dto } from './dto/create-{{kebabCase name}}.dto';
import { Update{{pascalCase name}}Dto } from './dto/update-{{kebabCase name}}.dto';
import { {{pascalCase name}}, Prisma } from '@prisma/client';

@Injectable()
export class {{pluralPascal name}}Service {
  private readonly logger = new Logger({{pluralPascal name}}Service.name);

  constructor(
    private prisma: PrismaService,
    private paginationHelper: PaginationHelper,
  ) {}

  async create(dto: Create{{pascalCase name}}Dto) {
    try {
      return await this.prisma.{{camelCase name}}.create({ data: dto });
    } catch (error) {
      this.logger.error(error.message || 'Unknown Error', error.stack);
      throw new InternalServerErrorException('Failed to create {{lowerCase name}}');
    }
  }

  async findAll(query: PaginationQueryDto) {
    const { search, page = 1, limit = 10 } = query;
    const args: Prisma.{{pascalCase name}}FindManyArgs = {
      where: search ? { name: { contains: search } } : {},
      orderBy: { createdAt: 'desc' },
    };
    return await this.paginationHelper.paginate<{{pascalCase name}}>(
      this.prisma.{{camelCase name}}, args, { page, limit }
    );
  }

  async findOne(id: number) {
    const data = await this.prisma.{{camelCase name}}.findUnique({ where: { id } });
    if (!data) throw new NotFoundException(`{{pascalCase name}} with ID ${id} not found`);
    return data;
  }

  async update(id: number, dto: Update{{pascalCase name}}Dto) {
    await this.findOne(id);
    try {
      return await this.prisma.{{camelCase name}}.update({ where: { id }, data: dto });
    } catch (error) {
      this.logger.error(error.message || 'Unknown Error', error.stack);
      throw new InternalServerErrorException('Failed to update {{lowerCase name}}');
    }
  }

  async remove(id: number) {
    await this.findOne(id);
    try {
      return await this.prisma.{{camelCase name}}.delete({ where: { id } });
    } catch (error) {
      this.logger.error(error.message || 'Unknown Error', error.stack);
      throw new InternalServerErrorException('Failed to delete {{lowerCase name}}');
    }
  }
}