<?php
// =============================================================
//  POST /api/v1/credentials/delete
//
//  Mirrors app/manage_credentials.php's own action=delete handler — a
//  hard delete, same as the desktop (there's no soft-delete/Revoked
//  workflow actually wired up anywhere in this codebase; the
//  `credentials.status` enum column exists in the schema but is never
//  read or written by any file, desktop or otherwise).
//
//  Body: { "id": 1 }
// =============================================================

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

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

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

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

$stmt = $conn->prepare('DELETE FROM credentials WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$deleted = $stmt->affected_rows > 0;
$stmt->close();

if (!$deleted) {
    Api::error(404, 'NotFound', 'Credential not found');
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'delete_credential', 'credential', $id, null, null);

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