import { ConflictError, NotFoundError } from "../../common/errors/http-errors";
import * as deptRepo from "./department.repo";

export async function createDepartment(organizationId: string, name: string) {
  const existing = await deptRepo.findDepartmentByName(organizationId, name);
  if (existing) throw new ConflictError("Department with this name already exists");
  return deptRepo.createDepartment({ organizationId, name });
}

export async function getDepartments(
  organizationId: string,
  page: number,
  limit: number,
  search?: string,
) {
  return deptRepo.findAllDepartments(organizationId, page, limit, search);
}

export async function getDepartment(id: string, organizationId: string) {
  const dept = await deptRepo.findDepartmentById(id, organizationId);
  if (!dept) throw new NotFoundError("Department not found");
  return dept;
}

export async function updateDepartment(id: string, organizationId: string, name: string) {
  const dept = await deptRepo.findDepartmentById(id, organizationId);
  if (!dept) throw new NotFoundError("Department not found");
  const existing = await deptRepo.findDepartmentByName(organizationId, name);
  if (existing && existing.id !== id) throw new ConflictError("Department with this name already exists");
  return deptRepo.updateDepartmentById(id, organizationId, name);
}

export async function deleteDepartment(id: string, organizationId: string) {
  const dept = await deptRepo.findDepartmentById(id, organizationId);
  if (!dept) throw new NotFoundError("Department not found");
  return deptRepo.deleteDepartmentById(id);
}
