<?php
// =============================================================
//  POST /api/v1/admin_allocations/unit_create
//
//  Wraps app/unit_assignment.php's own 'assign_unit' action —
//  assignUnitToSpecialtyDepartment() unmodified: refuses a unit already
//  assigned under this specialty+department, and refuses weeks beyond
//  what remains of the specialty-department's own allocation.
//
//  Body: { "specialty_id": 1, "department_id": 2, "unit_id": 3, "weeks": 4 }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/db_functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('manage_assignments');

$body = Api::body();
$specialtyId = (int)($body['specialty_id'] ?? 0);
$departmentId = (int)($body['department_id'] ?? 0);
$unitId = (int)($body['unit_id'] ?? 0);
$weeks = (int)($body['weeks'] ?? 0);

if (!$specialtyId || !$departmentId || !$unitId || $weeks < 1) {
    Api::error(422, 'ValidationError', 'Please fill in all fields correctly.');
}

$result = assignUnitToSpecialtyDepartment($conn, $specialtyId, $departmentId, $unitId, $weeks, $account->getId());
if (!$result['success']) {
    Api::error(409, 'AssignmentConflict', $result['message']);
}
$newId = $conn->insert_id;

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'assign_unit', 'department_unit_weeks', $newId, null, json_encode(['specialty_id' => $specialtyId, 'department_id' => $departmentId, 'unit_id' => $unitId, 'weeks' => $weeks]));

Api::success(['id' => $newId], [], 201);
