import { apiFetch } from "./http";
import type { DepartmentRecord, DepartmentRequest, PositionRecord, PositionRequest } from "./types";

export function listDepartments(activeOnly = true, keyword = ""): Promise<DepartmentRecord[]> {
  const params = new URLSearchParams();
  params.set("active_only", String(activeOnly));
  if (keyword.trim()) {
    params.set("keyword", keyword.trim());
  }
  return apiFetch<DepartmentRecord[]>(`/api/organization/departments?${params.toString()}`);
}

export function createDepartment(request: DepartmentRequest): Promise<DepartmentRecord> {
  return apiFetch<DepartmentRecord>("/api/organization/departments", {
    method: "POST",
    body: JSON.stringify(request),
  });
}

export function updateDepartment(id: number, request: DepartmentRequest): Promise<DepartmentRecord> {
  return apiFetch<DepartmentRecord>(`/api/organization/departments/${id}`, {
    method: "PUT",
    body: JSON.stringify(request),
  });
}

export function listPositions(
  departmentId?: number,
  activeOnly = true,
  keyword = "",
): Promise<PositionRecord[]> {
  const params = new URLSearchParams();
  params.set("active_only", String(activeOnly));
  if (departmentId) {
    params.set("department_id", String(departmentId));
  }
  if (keyword.trim()) {
    params.set("keyword", keyword.trim());
  }
  return apiFetch<PositionRecord[]>(`/api/organization/positions?${params.toString()}`);
}

export function createPosition(request: PositionRequest): Promise<PositionRecord> {
  return apiFetch<PositionRecord>("/api/organization/positions", {
    method: "POST",
    body: JSON.stringify(request),
  });
}

export function updatePosition(id: number, request: PositionRequest): Promise<PositionRecord> {
  return apiFetch<PositionRecord>(`/api/organization/positions/${id}`, {
    method: "PUT",
    body: JSON.stringify(request),
  });
}
