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

export async function getAllContractCategories(includeInactive = false) {
  return prisma.contractCategory.findMany({
    where: includeInactive ? {} : { isActive: true },
    orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
    include: {
      _count: {
        select: { contracts: true },
      },
    },
  });
}

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

export async function getContractCategoryByCode(code: string) {
  return prisma.contractCategory.findUnique({
    where: { code },
  });
}

interface ContractCategoryCreateData {
  code: string;
  name: string;
  icon?: string;
  color?: string;
  sortOrder?: number;
  isActive?: boolean;
}

export async function createContractCategory(data: ContractCategoryCreateData) {
  return prisma.contractCategory.create({
    data,
    include: {
      _count: {
        select: { contracts: true },
      },
    },
  });
}

export async function updateContractCategory(id: number, data: Partial<ContractCategoryCreateData>) {
  return prisma.contractCategory.update({
    where: { id },
    data,
    include: {
      _count: {
        select: { contracts: true },
      },
    },
  });
}

export async function deleteContractCategory(id: number) {
  // Check if category has contracts
  const category = await prisma.contractCategory.findUnique({
    where: { id },
    include: { _count: { select: { contracts: true } } },
  });

  if (category && category._count.contracts > 0) {
    throw new Error(`Kategorie kann nicht gelöscht werden, da ${category._count.contracts} Verträge zugeordnet sind.`);
  }

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