import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateTaskCategoryDto } from './dto/create-task-category.dto';
import { UpdateTaskCategoryDto } from './dto/update-task-category.dto';

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

  findAll() {
    return this.prisma.taskCategory.findMany({ orderBy: [{ group: 'asc' }, { name: 'asc' }] });
  }

  create(dto: CreateTaskCategoryDto) {
    return this.prisma.taskCategory.create({
      data: {
        name: dto.name,
        group: dto.group,
        code: dto.code,
        isSystem: dto.isSystem ?? false,
      },
    });
  }

  update(id: string, dto: UpdateTaskCategoryDto) {
    return this.prisma.taskCategory.update({
      where: { id },
      data: {
        ...(dto.name !== undefined && { name: dto.name }),
        ...(dto.group !== undefined && { group: dto.group }),
        ...(dto.code !== undefined && { code: dto.code }),
        ...(dto.isSystem !== undefined && { isSystem: dto.isSystem }),
      },
    });
  }

  async remove(id: string) {
    const [target] = await this.prisma.taskCategory.findMany({ where: { id }, take: 1 });
    if (!target || target.isSystem) return { deleted: false };
    await this.prisma.taskCategory.delete({ where: { id } });
    return { deleted: true };
  }
}
