import { db } from "@/lib/db"
import type { PrismaClient } from "@prisma/client"
import type { DepartmentInput } from "./schema"

const prisma = db as PrismaClient

export async function listDepartmentsWithChildren() {
  return prisma.department.findMany({
    orderBy: { name: "asc" },
    include: {
      children: { orderBy: { name: "asc" } },
      branch: { select: { id: true, name: true } }, 
    },
  })
}

export async function createDepartment(input: DepartmentInput) {
  return prisma.department.create({
    data: {
      name: input.name,
      branchId: input.branchId,
      children: input.subDepartments?.length
        ? {
            createMany: {
              data: input.subDepartments.map((s) => ({ name: s.name })),
            },
          }
        : undefined,
    },
    include: {
      children: true,
      branch: { select: { id: true, name: true } },
    },
  })
}

export async function deleteDepartment(id: string) {
  await prisma.subDepartment.deleteMany({ where: { departmentId: id } })
  return prisma.department.delete({ where: { id } })
}