<?php

namespace App\Http\Resources;

use App\FieldVisibility\FieldCatalogue;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @property FieldCatalogue $resource
 */
class FieldVisibilityResource extends JsonResource
{
    public static $wrap = '';

    /**
     * @var list<string>
     */
    private array $hidden;

    /**
     * @param list<string> $hidden
     */
    public function __construct(FieldCatalogue $catalogue, array $hidden)
    {
        parent::__construct($catalogue);

        $this->hidden = $hidden;
    }

    /**
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        $catalogue = $this->resource;
        $fields = $catalogue->fields();
        $hidden = array_values(array_intersect($this->hidden, array_column($fields, 'key')));

        return [
            'entity' => $catalogue->entity(),
            'groups' => $catalogue->groups(),
            'fields' => array_map(fn (array $field) => [
                'key' => $field['key'],
                'label' => $field['label'],
                'group' => $field['group'],
                'lockable' => $field['lockable'],
                'hidden' => in_array($field['key'], $hidden, true),
            ], $fields),
            'hidden' => $hidden,
            'total' => count($fields),
            'visible' => count($fields) - count($hidden),
        ];
    }
}
