import { EmployeesApi } from "omsorgcore-client-ts";
import { configFor, callApi } from "./apiClientHelpers.js";

// Kapselt /api/employees von omsorgCore (EmployeesController) über den generierten
// Client (omsorgcore-client-ts). Feldnamen sind camelCase, da ASP.NET Core
// standardmäßig camelCase-JSON ausgibt.

// dateOfBirth/entryDate/exitDate müssen als Date-Objekte übergeben werden - die generierten
// ...ToJSON-Funktionen rufen .toISOString() darauf auf, ein reiner "YYYY-MM-DD"-String aus einem
// <input type="date"> würde dabei crashen (siehe ordersApi.js für dasselbe Muster).
function toDatePayload(payload) {
  return {
    ...payload,
    dateOfBirth: payload.dateOfBirth ? new Date(payload.dateOfBirth) : payload.dateOfBirth,
    entryDate: payload.entryDate ? new Date(payload.entryDate) : payload.entryDate,
    exitDate: payload.exitDate ? new Date(payload.exitDate) : payload.exitDate
  };
}

export async function listEmployees(accessToken, { search, status, employmentType, page = 1, pageSize = 20 } = {}) {
  const api = new EmployeesApi(configFor(accessToken));
  return callApi(api.apiEmployeesGetRaw({ search, status, employmentType, page, pageSize }));
}

export async function createEmployee(accessToken, payload) {
  const api = new EmployeesApi(configFor(accessToken));
  return callApi(api.apiEmployeesPostRaw({ createEmployeeRequest: toDatePayload(payload) }));
}

export async function getEmployee(accessToken, id) {
  const api = new EmployeesApi(configFor(accessToken));
  return callApi(api.apiEmployeesIdGetRaw({ id }));
}

export async function updateEmployee(accessToken, id, payload) {
  const api = new EmployeesApi(configFor(accessToken));
  return callApi(api.apiEmployeesIdPutRaw({ id, updateEmployeeRequest: toDatePayload(payload) }));
}

export async function deleteEmployee(accessToken, id) {
  const api = new EmployeesApi(configFor(accessToken));
  return callApi(api.apiEmployeesIdDeleteRaw({ id }));
}
