<?php
declare(strict_types=1);
require_once __DIR__ . '/../../src/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

Auth::check();

if (!Rbac::can('short_links_view')) {
    json_out(['ok' => false, 'error' => 'forbidden'], 403);
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = trim((string) ($_GET['action'] ?? ''));

$avail = ShortLinksRepository::availability();
if (!$avail['ok']) {
    json_out([
        'ok' => false,
        'error' => 'service_unavailable',
        'reason' => $avail['error'] ?? 'unknown',
    ], 503);
}

if ($method === 'GET') {
    if ($action === 'dashboard') {
        json_out([
            'ok' => true,
            'public_base' => UrlShortenerDatabase::publicBase(),
            'bearers' => ShortLinksRepository::listBearers(),
            'signers' => ShortLinksRepository::listSigners(),
            'audit' => ShortLinksRepository::listAudit(40),
            'permissions' => [
                'can_operate' => Rbac::can('short_links_operate'),
                'can_admin' => Rbac::isGlobalAdmin(),
            ],
        ]);
    }
    if ($action === 'links') {
        $bearerId = (int) ($_GET['bearer_id'] ?? 0);
        if ($bearerId <= 0) {
            json_out(['ok' => false, 'error' => 'missing_bearer_id'], 400);
        }
        json_out([
            'ok' => true,
            'links' => ShortLinksRepository::listLinks($bearerId),
        ]);
    }
    json_out(['ok' => false, 'error' => 'unknown_action'], 400);
}

if ($method !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

$raw = file_get_contents('php://input') ?: '';
$body = json_decode($raw, true);
if (!is_array($body)) {
    json_out(['ok' => false, 'error' => 'invalid_json'], 400);
}

if ($action === 'mint_bearer') {
    if (!Rbac::can('short_links_operate')) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $result = ShortLinksRepository::mintBearer(
        (string) ($body['label'] ?? ''),
        !array_key_exists('can_temporary', $body) || !empty($body['can_temporary']),
        !empty($body['can_permanent']),
        (int) ($body['rate_limit_per_hour'] ?? 1000),
        !empty($body['mint_signer'])
    );
    if (empty($result['ok'])) {
        json_out(['ok' => false, 'error' => $result['error'] ?? 'failed'], 400);
    }
    $resp = [
        'ok' => true,
        'bearer_id' => $result['bearer_id'],
        'token' => $result['token'],
    ];
    if (isset($result['signer_key'])) {
        $resp['signer_key'] = $result['signer_key'];
        $resp['signer_id'] = $result['signer_id'];
    }
    json_out($resp);
}

if ($action === 'mint_signer') {
    if (!Rbac::can('short_links_operate')) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $result = ShortLinksRepository::mintSigner((string) ($body['label'] ?? ''));
    if (empty($result['ok'])) {
        json_out(['ok' => false, 'error' => $result['error'] ?? 'failed'], 400);
    }
    json_out([
        'ok' => true,
        'signer_id' => $result['id'],
        'signer_key' => $result['key'],
    ]);
}

if ($action === 'revoke_signer') {
    if (!Rbac::can('short_links_operate')) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $signerId = (int) ($body['signer_id'] ?? 0);
    if ($signerId <= 0) {
        json_out(['ok' => false, 'error' => 'missing_signer_id'], 400);
    }
    if (!ShortLinksRepository::revokeSigner($signerId)) {
        json_out(['ok' => false, 'error' => 'not_found_or_revoked'], 404);
    }
    json_out(['ok' => true]);
}

if ($action === 'revoke_bearer') {
    if (!Rbac::can('short_links_operate')) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $bearerId = (int) ($body['bearer_id'] ?? 0);
    if ($bearerId <= 0) {
        json_out(['ok' => false, 'error' => 'missing_bearer_id'], 400);
    }
    if (!ShortLinksRepository::revokeBearer($bearerId)) {
        json_out(['ok' => false, 'error' => 'not_found_or_revoked'], 404);
    }
    json_out(['ok' => true]);
}

if ($action === 'create_link') {
    if (!Rbac::can('short_links_operate')) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $bearerId = (int) ($body['bearer_id'] ?? 0);
    $url = (string) ($body['url'] ?? '');
    $ttl = (int) ($body['ttl'] ?? 86400);
    if ($bearerId <= 0 || trim($url) === '') {
        json_out(['ok' => false, 'error' => 'missing_fields'], 400);
    }
    $result = ShortLinksRepository::createLink(
        $bearerId,
        $url,
        $ttl,
        (string) ($body['signer'] ?? '')
    );
    if (empty($result['ok'])) {
        $code = match ($result['error'] ?? '') {
            'rate_limited' => 429,
            'ttl_expired' => 409,
            'signer_required' => 403,
            default => 400,
        };
        json_out(['ok' => false, 'error' => $result['error'] ?? 'failed', 'message' => $result['message'] ?? ''], $code);
    }
    json_out(['ok' => true, 'link' => $result]);
}

if ($action === 'purge_expired') {
    if (!Rbac::isGlobalAdmin()) {
        json_out(['ok' => false, 'error' => 'forbidden'], 403);
    }
    $counts = ShortLinksRepository::purgeExpired();
    json_out(['ok' => true, 'purged' => $counts]);
}

json_out(['ok' => false, 'error' => 'unknown_action'], 400);
