import prisma from '../lib/prisma.js';

export async function getAllContractDurations(includeInactive = false) {
  const where = includeInactive ? {} : { isActive: true };
  return prisma.contractDuration.findMany({
    where,
    orderBy: { code: 'asc' },
  });
}

export async function getContractDurationById(id: number) {
  return prisma.contractDuration.findUnique({
    where: { id },
    include: {
      _count: {
        select: { contracts: true },
      },
    },
  });
}

export async function createContractDuration(data: {
  code: string;
  description: string;
}) {
  return prisma.contractDuration.create({
    data: {
      ...data,
      isActive: true,
    },
  });
}

export async function updateContractDuration(
  id: number,
  data: {
    code?: string;
    description?: string;
    isActive?: boolean;
  }
) {
  return prisma.contractDuration.update({
    where: { id },
    data,
  });
}

export async function deleteContractDuration(id: number) {
  // Check if contract duration is used by any contracts
  const count = await prisma.contract.count({
    where: { contractDurationId: id },
  });

  if (count > 0) {
    throw new Error(
      `Laufzeit kann nicht gelöscht werden, da sie von ${count} Verträgen verwendet wird`
    );
  }

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