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

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

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

    return this.prisma.relationshipType.create({
      data: {
        tenantId,
        name: dto.name,
        sortOrder: dto.sortOrder ?? 0,
      },
    });
  }

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

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

    if (!relType) {
      throw new NotFoundException('Beziehungstyp nicht gefunden');
    }

    return relType;
  }

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

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

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

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

    if (relType._count.relationships > 0) {
      throw new ConflictException(
        `Beziehungstyp kann nicht geloescht werden — ${relType._count.relationships} Beziehungen zugeordnet`,
      );
    }

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