<?php

namespace App\Master\Http\Resources;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use JsonSerializable;

class UserListResource extends JsonResource
{
    /**
     * @var LengthAwarePaginator
     */
    public $resource;

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array|Arrayable|JsonSerializable
     */
    public function toArray($request)
    {
        $this->resource = $this->resource
            ->through(fn($user) => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'profile_photo_url' => $user->profile_photo_url,
                'tenants' => $user->hasRole('mtc')
                    ? [['name' => 'Superadmin']]
                    : $user->tenants->map(fn($tenant) => [
                        'name' => $tenant->name,
                        'role' => $tenant->pivot->role,
                    ])
            ]);

        return parent::toArray($request);
    }
}
