<?php
// =============================================================
//  POST /api/v1/admin_allocations/unit_restore
//
//  Wraps app/trash.php's 'restore_unit' action — restoreUnitAssignment()
//  unmodified: refuses the restore if an Active assignment for this
//  same specialty-department-unit triple already exists, or if the
//  parent specialty→department allocation no longer has enough
//  remaining weeks to cover this assignment's own weeks (both real,
//  independently possible races while the row sat in the trash).
//
//  Body: { "id": 5 }
// =============================================================

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();
$id = (int)($body['id'] ?? 0);
if (!$id) Api::error(422, 'ValidationError', 'Invalid assignment');

$result = restoreUnitAssignment($conn, $id, $account->getFullName());
if (!$result['success']) {
    Api::error(409, 'RestoreFailed', $result['message']);
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'restore_unit_assignment', 'department_unit_weeks', $id);

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