import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateCommentTypeDto } from './dto/create-comment-type.dto';
import { UpdateCommentTypeDto } from './dto/update-comment-type.dto';

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

  async create(dto: CreateCommentTypeDto) {
    const name = dto.name.trim();

    const duplicate = await this.prisma.commentType.findFirst({
      where: {
        deletedAt: null,
        name: {
          equals: name,
          mode: 'insensitive',
        },
      },
    });

    if (duplicate) {
      throw new ConflictException('Comment type already exists');
    }

    return this.prisma.commentType.create({
      data: {
        name,
        description: dto.description?.trim() ?? null,
      },
    });
  }

  async findAll() {
    return this.prisma.commentType.findMany({
      where: {
        deletedAt: null,
      },
      orderBy: {
        id: 'asc',
      },
    });
  }

  async findOne(id: number) {
    const data = await this.prisma.commentType.findFirst({
      where: {
        id,
        deletedAt: null,
      },
    });

    if (!data) {
      throw new NotFoundException('Comment type not found');
    }

    return data;
  }

  async update(id: number, dto: UpdateCommentTypeDto) {
    await this.findOne(id);

    if (dto.name) {
      const name = dto.name.trim();
      const duplicate = await this.prisma.commentType.findFirst({
        where: {
          id: { not: id },
          deletedAt: null,
          name: {
            equals: name,
            mode: 'insensitive',
          },
        },
      });

      if (duplicate) {
        throw new ConflictException('Comment type name already exists');
      }
    }

    return this.prisma.commentType.update({
      where: { id },
      data: {
        ...(dto.name && {
          name: dto.name.trim(),
        }),
        ...(dto.description !== undefined && {
          description: dto.description?.trim() || null,
        }),
      },
    });
  }

  async remove(id: number) {
    await this.findOne(id);

    return this.prisma.commentType.update({
      where: { id },
      data: {
        deletedAt: new Date(),
      },
    });
  }
}
