<?php
// =============================================================
//  POST /api/v1/admin_rbac/roles_delete
//
//  Wraps app/roles.php's delete_role handler exactly, including both
//  of its safety rules: system roles (is_system = 1) can never be
//  deleted, and a role with users still assigned to it must be
//  reassigned first. role_permissions rows for the role are cleaned
//  up before the role itself is deleted, same order as the desktop page.
//
//  Body: { "role_id": 7 }
// =============================================================

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

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

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

$body   = Api::body();
$roleId = (int)($body['role_id'] ?? 0);
if ($roleId <= 0) Api::error(422, 'ValidationError', 'A valid role_id is required.');

$check = $conn->prepare("SELECT is_system, display_name FROM roles WHERE id = ?");
$check->bind_param('i', $roleId);
$check->execute();
$role = $check->get_result()->fetch_assoc();
$check->close();

if (!$role) {
    Api::error(404, 'NotFound', 'Role not found. It may have already been deleted.');
}

if ($role['is_system']) {
    Api::error(409, 'ProtectedRole', '"' . $role['display_name'] . '" is a protected system role and cannot be deleted.');
}

$userCheck = $conn->prepare("SELECT COUNT(*) AS count FROM users WHERE role_id = ?");
$userCheck->bind_param('i', $roleId);
$userCheck->execute();
$userCount = (int)$userCheck->get_result()->fetch_assoc()['count'];
$userCheck->close();

if ($userCount > 0) {
    Api::error(409, 'RoleInUse', "Cannot delete \"{$role['display_name']}\" because $userCount user(s) are currently assigned to it. Reassign those users to a different role first, then come back to delete this one.");
}

$conn->begin_transaction();
try {
    $delPerm = $conn->prepare("DELETE FROM role_permissions WHERE role_id = ?");
    $delPerm->bind_param('i', $roleId);
    $delPerm->execute();
    $delPerm->close();

    $stmt = $conn->prepare("DELETE FROM roles WHERE id = ?");
    $stmt->bind_param('i', $roleId);
    if (!$stmt->execute()) {
        throw new RuntimeException($stmt->error);
    }
    $stmt->close();
    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    Api::error(500, 'ServerError', 'Database error while deleting role: ' . $e->getMessage());
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'delete_role', 'role', $roleId, json_encode(['display_name' => $role['display_name']]), null);

Api::success(['message' => "Role \"{$role['display_name']}\" was deleted successfully."]);
