<?php

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

Guard::requireLogin();
Guard::requireAbilityOrForbidden(BookmarksAuthorizationPolicy::ABILITY_USE);

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;
}

$type = trim((string) requestInput()->body('type'));
$rawItems = requestInput()->body('items');

$items = is_array($rawItems) ? $rawItems : (is_string($rawItems) ? json_decode($rawItems, true) : []);
if (!is_array($items) || $items === []) {
    http_response_code(400);
    Router::json(['ok' => false, 'error' => 'invalid_items']);
    return;
}

$service = app(BookmarkService::class);

if ($type === 'root') {
    $rootPairs = [];
    $seenRootIds = [];
    $seenSortOrders = [];

    foreach ($items as $item) {
        if (!is_array($item)) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        $kind = trim((string) ($item['kind'] ?? ''));
        $id = (int) ($item['id'] ?? 0);
        $sortOrder = (int) ($item['sort_order'] ?? 0);
        if (($kind !== 'group' && $kind !== 'bookmark') || $id <= 0 || $sortOrder <= 0) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        $dedupeKey = $kind . ':' . $id;
        if (isset($seenRootIds[$dedupeKey]) || isset($seenSortOrders[$sortOrder])) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        $seenRootIds[$dedupeKey] = true;
        $seenSortOrders[$sortOrder] = true;
        $rootPairs[] = ['kind' => $kind, 'id' => $id, 'sort_order' => $sortOrder];
    }

    $result = $service->reorderRootFromItems($userId, $rootPairs);
} else {
    $pairs = [];
    $seenIds = [];

    foreach ($items as $item) {
        if (!is_array($item)) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        $id = (int) ($item['id'] ?? 0);
        $sortOrder = (int) ($item['sort_order'] ?? 0);
        if ($id <= 0 || $sortOrder <= 0) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        if (isset($seenIds[$id])) {
            http_response_code(400);
            Router::json(['ok' => false, 'error' => 'invalid_items']);
            return;
        }
        $seenIds[$id] = true;
        $pairs[] = ['id' => $id, 'sort_order' => $sortOrder];
    }

    $result = $service->reorderFromItems($userId, $type, $pairs);
}

if ($result['ok']) {
    app(SessionStoreInterface::class)->set('module.bookmarks.grouped', $service->listGroupedForUser($userId));
    Router::json(['ok' => true]);
    return;
}

http_response_code(400);
Router::json($result);
