<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Module\Bookmarks\Service\BookmarkService;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

Guard::requireLogin();

if (requestInput()->method() !== 'POST') {
    http_response_code(405);
    Router::json(['ok' => false, 'error' => 'method_not_allowed']);
    return;
}

if (!Session::checkCsrfToken()) {
    http_response_code(403);
    Router::json(['ok' => false, 'error' => 'csrf']);
    return;
}

$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
if ($userId <= 0) {
    http_response_code(401);
    Router::json(['ok' => false, 'error' => 'unauthorized']);
    return;
}

$name = trim((string) requestInput()->body('name'));
$icon = trim((string) requestInput()->body('icon'));
$groupId = requestInput()->body('id');
$groupId = ($groupId !== null && $groupId !== '') ? (int) $groupId : null;

$service = app(BookmarkService::class);
$result = $service->saveGroup($userId, $name, $icon, $groupId);

if ($result['ok']) {
    app(SessionStoreInterface::class)->set('module.bookmarks.grouped', $service->listGroupedForUser($userId));
} else {
    http_response_code(400);
}

Router::json($result);
