<?php

declare(strict_types=1);

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\Collections\ReorderSavedCollectionListItemsRequest;
use App\Models\Collection;
use App\Models\CollectionSavedList;
use App\Services\CollectionSavedLibraryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CollectionSavedLibraryController extends Controller
{
    public function __construct(
        private readonly CollectionSavedLibraryService $savedLibrary,
    ) {
    }

    public function storeList(Request $request): JsonResponse
    {
        $list = $this->savedLibrary->createList(
            $request->user(),
            (string) $request->validate([
                'title' => ['required', 'string', 'min:2', 'max:120'],
            ])['title'],
        );

        return response()->json([
            'ok' => true,
            'list' => [
                'id' => (int) $list->id,
                'title' => $list->title,
                'slug' => $list->slug,
                'items_count' => 0,
                'url' => route('me.saved.collections.lists.show', ['listSlug' => $list->slug]),
            ],
        ]);
    }

    public function storeItem(Request $request, Collection $collection): JsonResponse
    {
        $payload = $request->validate([
            'saved_list_id' => ['required', 'integer', 'exists:collection_saved_lists,id'],
        ]);

        $list = CollectionSavedList::query()->findOrFail((int) $payload['saved_list_id']);
        $item = $this->savedLibrary->addToList($request->user(), $list, $collection);

        return response()->json([
            'ok' => true,
            'added' => $item->wasRecentlyCreated,
            'item' => [
                'id' => (int) $item->id,
                'saved_list_id' => (int) $item->saved_list_id,
                'collection_id' => (int) $item->collection_id,
                'order_num' => (int) $item->order_num,
            ],
            'list' => [
                'id' => (int) $list->id,
                'items_count' => $this->savedLibrary->itemsCount($list),
            ],
        ]);
    }

    public function destroyItem(Request $request, CollectionSavedList $list, Collection $collection): JsonResponse
    {
        $removed = $this->savedLibrary->removeFromList($request->user(), $list, $collection);

        return response()->json([
            'ok' => true,
            'removed' => $removed,
            'list' => [
                'id' => (int) $list->id,
                'items_count' => $this->savedLibrary->itemsCount($list),
            ],
        ]);
    }

    public function reorderItems(ReorderSavedCollectionListItemsRequest $request, CollectionSavedList $list): JsonResponse
    {
        $orderedCollectionIds = $request->validated('collection_ids');

        $this->savedLibrary->reorderList($request->user(), $list, $orderedCollectionIds);

        return response()->json([
            'ok' => true,
            'list' => [
                'id' => (int) $list->id,
                'items_count' => $this->savedLibrary->itemsCount($list),
            ],
            'ordered_collection_ids' => collect($orderedCollectionIds)
                ->map(static fn ($id) => (int) $id)
                ->values()
                ->all(),
        ]);
    }

        public function updateNote(Request $request, Collection $collection): JsonResponse
        {
            $payload = $request->validate([
                'note' => ['nullable', 'string', 'max:1000'],
            ]);

            $note = $this->savedLibrary->upsertNote($request->user(), $collection, $payload['note'] ?? null);

            return response()->json([
                'ok' => true,
                'note' => $note ? [
                    'collection_id' => (int) $note->collection_id,
                    'note' => (string) $note->note,
                ] : null,
            ]);
        }
}
