import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { CrmPrismaService } from '../prisma/crm-prisma.service';
import { CreateDealTypeDto } from './dto/create-deal-type.dto';
import { UpdateDealTypeDto } from './dto/update-deal-type.dto';

@Injectable()
export class DealTypesService {
  constructor(private readonly prisma: CrmPrismaService) {}

  async create(tenantId: string, dto: CreateDealTypeDto) {
    const existing = await this.prisma.dealType.findUnique({
      where: { tenantId_name: { tenantId, name: dto.name } },
    });
    if (existing) {
      throw new ConflictException(
        `Vorgangsart "${dto.name}" existiert bereits`,
      );
    }

    return this.prisma.dealType.create({
      data: {
        tenantId,
        name: dto.name,
        color: dto.color ?? '#6B7280',
        sortOrder: dto.sortOrder ?? 0,
      },
    });
  }

  async findAll(tenantId: string) {
    return this.prisma.dealType.findMany({
      where: { tenantId },
      orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
      include: {
        _count: { select: { deals: true } },
      },
    });
  }

  async findOne(tenantId: string, id: string) {
    const dealType = await this.prisma.dealType.findFirst({
      where: { id, tenantId },
      include: {
        _count: { select: { deals: true } },
      },
    });

    if (!dealType) {
      throw new NotFoundException('Vorgangsart nicht gefunden');
    }

    return dealType;
  }

  async update(tenantId: string, id: string, dto: UpdateDealTypeDto) {
    await this.findOne(tenantId, id);

    if (dto.name) {
      const existing = await this.prisma.dealType.findFirst({
        where: { tenantId, name: dto.name, NOT: { id } },
      });
      if (existing) {
        throw new ConflictException(
          `Vorgangsart "${dto.name}" existiert bereits`,
        );
      }
    }

    return this.prisma.dealType.update({
      where: { id },
      data: dto,
      include: {
        _count: { select: { deals: true } },
      },
    });
  }

  async remove(tenantId: string, id: string) {
    const dealType = await this.findOne(tenantId, id);

    if (dealType._count.deals > 0) {
      throw new ConflictException(
        `Vorgangsart kann nicht geloescht werden — ${dealType._count.deals} Vorgang/Vorgaenge zugeordnet`,
      );
    }

    return this.prisma.dealType.delete({ where: { id } });
  }
}
