import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { CrmPrismaService } from '../prisma/crm-prisma.service';
import { CreateIndustryDto } from './dto/create-industry.dto';
import { UpdateIndustryDto } from './dto/update-industry.dto';

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

  async create(tenantId: string, dto: CreateIndustryDto) {
    // Pruefen ob Name bereits existiert
    const existing = await this.prisma.industry.findUnique({
      where: { tenantId_name: { tenantId, name: dto.name } },
    });
    if (existing) {
      throw new ConflictException(
        `Branche "${dto.name}" existiert bereits`,
      );
    }

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

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

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

    if (!industry) {
      throw new NotFoundException('Branche nicht gefunden');
    }

    return industry;
  }

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

    // Name-Uniqueness pruefen falls Name geaendert wird
    if (dto.name) {
      const existing = await this.prisma.industry.findFirst({
        where: { tenantId, name: dto.name, NOT: { id } },
      });
      if (existing) {
        throw new ConflictException(
          `Branche "${dto.name}" existiert bereits`,
        );
      }
    }

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

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

    // Pruefen ob noch Unternehmen zugeordnet sind
    if (industry._count.companies > 0) {
      throw new ConflictException(
        `Branche kann nicht geloescht werden — ${industry._count.companies} Unternehmen zugeordnet`,
      );
    }

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