<?php
// =============================================================
//  POST /api/v1/admin_allocations/specialty_department_create
//
//  Wraps app/specialty_department.php's own 'assign_specialty' action —
//  same duplicate-allocation check and the same underlying
//  assignSpecialtyToDepartment() write. That shared function
//  (include/db_functions.php) was fixed alongside this endpoint: its
//  own duplicate check only looks at is_active='Active' rows, but the
//  specialty_department_weeks table's UNIQUE(specialty_id, department_id)
//  index isn't scoped to is_active — so re-creating an allocation whose
//  prior row was soft-deleted always collided with that index and threw
//  an uncaught duplicate-key exception (a real, pre-existing defect this
//  endpoint's own device verification surfaced, also present on
//  app/specialty_department.php and app/assign_department_unit.php).
//  The shared function now reactivates the soft-deleted row instead.
//
//  Body: { "specialty_id": 1, "department_id": 2, "weeks": 8 }
// =============================================================

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();
$specialtyId = (int)($body['specialty_id'] ?? 0);
$departmentId = (int)($body['department_id'] ?? 0);
$weeks = (int)($body['weeks'] ?? 0);

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

$result = assignSpecialtyToDepartment($conn, $specialtyId, $departmentId, $weeks, $account->getId());
if (!$result['success']) {
    Api::error(409, 'DuplicateAllocation', $result['message']);
}
// assignSpecialtyToDepartment() returns the real row id itself now — it
// may have reactivated a previously soft-deleted row (an UPDATE, not an
// INSERT) rather than inserting a new one, so $conn->insert_id can't be
// trusted here even before logAudit()'s own INSERT would otherwise
// overwrite it.
$newId = $result['id'];

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

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