<?php

namespace App\Http\Resources;

use App\Facades\Feature;
use App\Traits\ResolvesSiteFavicon;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Tenant;
use Mtc\Notifications\Facades\Notification;

class UserResource extends JsonResource
{
    use ResolvesSiteFavicon;

    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    #[\Override]
    public function toArray($request)
    {
        $this->resource
            ->load([
                'tenants',
                'roles',
                'permissions',
            ]);


        if (session('current_tenant')) {
            $tenantId = session('current_tenant');
        } elseif ($this->resource->tenants()->count() == 1) {
            $tenantId = $this->resource->tenants()->first()->id;
        }

        if (!empty($tenantId)) {
            tenancy()->initialize($tenantId);
            setPermissionsTeamId(tenant('id'));
            $this->resource->has_notifications = Notification::hasUnread($this->resource);
            $this->resource->selected_site_id = tenant('id');
            $this->resource->tier = tenant('tier');
            $this->resource->features = tenant()->features->pluck('feature');
            tenancy()->end();
        }

        if ($this->hasSuperAdminRole() === false) {
            $this->setUserRoleValue();
        }

        $this->tenantDataVisibility();
        $user = $this->resource->toArray();
        $user['permissions'] = $this->resource->getAllPermissions()->pluck('name');
        $user['is_impersonated'] = session()->has('impersonate');
        return $user;
    }

    private function hasSuperAdminRole(): bool
    {
        return $this->resource->roles
                ->filter(fn ($role) => $role->name === 'mtc')
                ->count() > 0;
    }

    private function setUserRoleValue(): void
    {
        if ($this->resource->tenants->count() > 1) {
            $this->resource->role = $this->resource->tenants
                ->filter(fn ($tenant) => $tenant->id === session('current_tenant'))
                ->map(fn ($tenant) => $tenant->pivot?->role)
                ->first();
        } else {
            $this->resource->role = $this->resource->tenants
                ->first()
                ?->pivot?->role;
        }
    }

    private function tenantDataVisibility(): void
    {
        $this->resource->tenants
            ->each(function (Tenant $tenant) {
                $tenant->features = Feature::enabledForTenant();
                $tenant->primary_domain = $tenant->domains->where('primary', 1)->first()?->domain;
                tenancy()->initialize($tenant);
                $tenant->icon = $this->resolveSiteFavicon($tenant);
                tenancy()->end();
            })
            ->each(fn (Tenant $tenant) => $tenant->setVisible([
                'id',
                'name',
                'tier',
                'primary_domain',
                'icon',
                'features'
            ]));
    }
}
