<?php

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\System\NavItemReorderRequest;
use App\Http\Requests\System\NavItemStoreRequest;
use App\Http\Resources\System\NavBuilderDataResource;
use App\Http\Resources\System\NavItemResource;
use App\Models\NavItem;
use App\Services\Navigation\NavBuilderService;
use App\Services\Navigation\NavbarService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class NavBuilderController extends BaseApiController
{
    public function __construct(
        private NavBuilderService $builderService,
        private NavbarService $navbarService
    ) {
        parent::__construct();
    }

    public function menu(): JsonResponse
    {
        $user = auth()->user();
        $roles = $user?->roles()->pluck('roles.name')->map(fn ($name) => strtolower((string) $name))->toArray() ?? [];

        $menu = $this->navbarService->getMenuForRoles($roles);

        return $this->success([
            'items' => NavItemResource::collection($menu),
        ]);
    }

    public function data(): JsonResponse
    {
        $this->authorize('manage', NavItem::class);

        $payload = $this->builderService->getAdminPayload();

        return $this->success([
            'data' => new NavBuilderDataResource($payload),
        ]);
    }

    public function store(NavItemStoreRequest $request): JsonResponse
    {
        $this->authorize('manage', NavItem::class);

        $result = $this->builderService->save($request->validated());

        if (empty($result['ok'])) {
            return $this->error($result['message'] ?? 'Unable to save menu item.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success([
            'id' => $result['id'],
        ], 'Menu saved.', Response::HTTP_CREATED);
    }

    public function destroy(int $id): JsonResponse
    {
        $this->authorize('manage', NavItem::class);

        $deleted = $this->builderService->delete($id);

        if (!$deleted) {
            return $this->error('Menu item not found.', Response::HTTP_NOT_FOUND);
        }

        return $this->success(null, 'Menu item deleted.');
    }

    public function reorder(NavItemReorderRequest $request): JsonResponse
    {
        $this->authorize('manage', NavItem::class);

        try {
            $this->builderService->reorder($request->validated()['orders']);
        } catch (\Throwable $e) {
            Log::error('Nav reorder failed: ' . $e->getMessage());
            return $this->error('Unable to reorder items.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(['ok' => true], 'Menu reordered.');
    }
}
