<?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;

    protected $impersonationStatuses;

    public function __construct($resource, $impersonationStatuses = null)
    {
        parent::__construct($resource);
        $this->impersonationStatuses = $impersonationStatuses;
    }

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array|Arrayable|JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $statuses = $this->impersonationStatuses;

        $this->resource = $this->resource
            ->through(function ($user) use ($statuses) {
                $data = [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'profile_photo_url' => $user->profile_photo_url,
                    'has_mtc_role' => $user->hasRole('mtc'),
                    'tenants' => $user->hasRole('mtc')
                        ? [['name' => 'Superadmin']]
                        : $user->tenants->map(fn ($tenant) => [
                            'name' => $tenant->name,
                            'role' => $tenant->pivot->role,
                        ]),
                ];

                if ($statuses !== null) {
                    $userStatus = $statuses->get($user->id);
                    $data['has_pending_request'] = $userStatus['has_pending_request'] ?? false;
                    $data['has_usable_request'] = $userStatus['has_usable_request'] ?? false;
                }

                return $data;
            });

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