<?php

namespace App\Http\Controllers;

use App\FieldVisibility\FieldCatalogueRegistry;
use App\Http\Requests\UpdateFieldVisibilityRequest;
use App\Http\Resources\FieldVisibilityResource;
use App\TenantHiddenFieldRepository;
use Symfony\Component\HttpFoundation\Response;

class FieldVisibilityController extends Controller
{
    public function __construct(
        private readonly FieldCatalogueRegistry $registry,
        private readonly TenantHiddenFieldRepository $repository,
    ) {
    }

    public function show(string $entity): FieldVisibilityResource
    {
        abort_unless($this->registry->has($entity), Response::HTTP_NOT_FOUND);

        return new FieldVisibilityResource(
            $this->registry->for($entity),
            $this->repository->hiddenKeys($entity),
        );
    }

    public function update(UpdateFieldVisibilityRequest $request, string $entity): FieldVisibilityResource
    {
        abort_unless($this->registry->has($entity), Response::HTTP_NOT_FOUND);

        $this->repository->sync($entity, $request->validated()['hidden']);

        return new FieldVisibilityResource(
            $this->registry->for($entity),
            $this->repository->hiddenKeys($entity),
        );
    }
}
