<?php
// =============================================================
//  POST /api/v1/rotations/nurse_generate
//
//  The Hybrid Distribution algorithm's generation write path for nurse
//  rotations, extracted from app/create_nurse_rotation.php's assign_rotation
//  handler into app/rotation_generation_service.php (see that file's header
//  for the full extraction and correctness notes — in particular, this
//  endpoint enforces hard AI conflict blocking correctly, unlike the
//  desktop page's own currently-unreachable gate, unless the caller
//  explicitly passes force_assign: true after reviewing the conflicts).
//
//  Request body:
//    {
//      "nurse_ids": [1,2,3],
//      "department_ids": [4,5],
//      "start_date": "2026-09-01",
//      "preceptor_id": 12,                 // optional
//      "enable_comprehensive_rotation": true,
//      "force_assign": false               // set true to proceed despite hard AI conflicts
//    }
//
//  Responses:
//    200 — assigned. data: { success_count, schedule_count, error_messages,
//          ai_score_result, ai_conflicts, ai_sequence_warnings, ai_anomalies,
//          sms_sent_count, sms_total_count }
//    409 — blocked by hard AI conflicts (force_assign not set). data carries
//          the same ai_* fields so the client can show them and re-submit
//          with force_assign: true.
//    422 — validation failure (no valid nurses/departments, etc.)
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../app/ai_rotation_engine.php';
require_once __DIR__ . '/../../../app/rotation_generation_service.php';
require_once __DIR__ . '/../../../include/account_helpers.php';
require_once __DIR__ . '/../../../services/VelstackServiceProvider.php';
require_once __DIR__ . '/../../../include/notification_queue.php';

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

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

$body = Api::body();

$nurseIds = array_values(array_unique(array_map('intval', (array)($body['nurse_ids'] ?? []))));
$deptIds  = array_values(array_unique(array_map('intval', (array)($body['department_ids'] ?? []))));
$startDate = (string)($body['start_date'] ?? '');
$preceptorId = isset($body['preceptor_id']) && $body['preceptor_id'] !== null && $body['preceptor_id'] !== ''
    ? (int)$body['preceptor_id'] : null;
$enableComprehensive = (bool)($body['enable_comprehensive_rotation'] ?? false);
$forceAssign = (bool)($body['force_assign'] ?? false);

if (empty($nurseIds)) {
    Api::error(422, 'ValidationError', 'nurse_ids must be a non-empty array');
}
if (empty($deptIds)) {
    Api::error(422, 'ValidationError', 'department_ids must be a non-empty array');
}

$result = generateNurseRotationBatch(
    $conn,
    $account->getId(),
    $nurseIds,
    $deptIds,
    $startDate,
    $preceptorId,
    $enableComprehensive,
    $forceAssign
);

if ($result['blocked_by_ai']) {
    Api::error(409, 'BlockedByAiConflicts', $result['message'], [
        'ai_conflicts'          => $result['ai_conflicts'],
        'ai_score_result'       => $result['ai_score_result'],
        'ai_sequence_warnings'  => $result['ai_sequence_warnings'],
        'ai_assigned_nurse_ids' => $result['ai_assigned_nurse_ids'],
    ]);
}

if (!$result['ok']) {
    Api::error(422, 'AssignmentFailed', $result['message'] ?? 'Assignment failed.');
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'assign_rotations', 'nurse_rotation', null, null, json_encode([
    'nurse_count' => $result['success_count'],
    'department_ids' => $deptIds,
]));

Api::success([
    'success_count'         => $result['success_count'],
    'schedule_count'        => $result['schedule_count'],
    'error_messages'        => $result['error_messages'],
    'ai_score_result'       => $result['ai_score_result'],
    'ai_conflicts'          => $result['ai_conflicts'],
    'ai_sequence_warnings'  => $result['ai_sequence_warnings'],
    'ai_anomalies'          => $result['ai_anomalies'],
    'ai_assigned_nurse_ids' => $result['ai_assigned_nurse_ids'],
    'sms_sent_count'        => $result['sms_sent_count'],
    'sms_total_count'       => $result['sms_total_count'],
]);
