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

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

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

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

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

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

    if (!accountType) {
      throw new NotFoundException('Kontotyp nicht gefunden');
    }

    return accountType;
  }

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

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

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

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

    if (accountType._count.companies > 0) {
      throw new ConflictException(
        `Kontotyp kann nicht geloescht werden — ${accountType._count.companies} Unternehmen zugeordnet`,
      );
    }

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