<?php
// =============================================================
//  POST /api/v1/admin_allocations/specialty_department_delete
//
//  Wraps app/specialty_department.php's own 'soft_delete_specialty_dept'
//  action — softDeleteSpecialtyDepartment() refuses the delete (with a
//  clear message) if any department_unit_weeks rows still reference
//  this allocation, otherwise sets is_active='Inactive' plus
//  deleted_by/deleted_at. No reason is collected, matching the desktop
//  page's own plain confirm dialog ("This allocation will be
//  permanently removed") — deletion_reason exists as a column on
//  specialty_department_weeks but the desktop write path never
//  populates it either, so this endpoint doesn't invent a value for it.
//
//  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_allocations');

$body = Api::body();
$id = (int)($body['id'] ?? 0);
if (!$id) Api::error(422, 'ValidationError', 'Invalid allocation');

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

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

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