<?php

namespace App\Master\Http\Resources;

use App\Master\Models\ApiToken;
use App\Services\ApiAuthenticatedRoutes;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Tenant;

class ApiUserView extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        $this->resource->load('tokens', 'allowedRoutes');
        $this->resource->token_types = [
            [
                'name' => 'OAuth flow to get access token',
                'value' => ApiToken::TYPE_OAUTH,
            ],
            [
                'name' => 'Simple persistent API Token',
                'value' => ApiToken::TYPE_PERSISTENT,
            ],
        ];

        $this->resource->tenants = $this->resource->tenants->pluck('tenant_id');
        $this->resource['tenant_list'] = Tenant::all()->map(fn (Tenant $tenant) => [
            'name' => $tenant->name,
            'value' => $tenant->id,
        ]);
        if (!empty($this->resource->client_secret)) {
            $this->resource->client_secret = decrypt($this->resource->client_secret);
        }

        $resource = $this->resource->toArray();

        $resource['available_routes'] = $this->getRoutes();
        $resource['allowed_routes'] = $this->resource->allowedRoutes->map(fn ($route) => [
            'name' => $route->route_name,
        ])->values();

        return $resource;
    }

    private function getRoutes(): Collection
    {
        return app(ApiAuthenticatedRoutes::class)->names()
            ->map(fn (string $name) => [
                'name' => $name,
            ])
            ->values();
    }
}
