<?php

namespace App\Http\Resources;

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

class UserResource extends JsonResource
{
    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;
                $tenant->icon = Settings::get('site-favicon') ?? $this->placeholder($tenant);
            })
            ->each(fn(Tenant $tenant) => $tenant->setVisible([
                'id',
                'name',
                'tier',
                'primary_domain',
                'icon',
                'features'
            ]));
    }

    private function placeholder(Tenant $site): array
    {
        return [
            'url' => 'https://ui-avatars.com/api/?name=' . urlencode($site->name) . '&color=7F9CF5&background=EBF4FF'
        ];
    }
}
