<?php

namespace App\Master\Http\Resources;

use App\Facades\Settings;
use App\TierHelper;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\LengthAwarePaginator;
use JsonSerializable;
use Mtc\MercuryDataModels\Tenant;
use Symfony\Component\Intl\Currencies;

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

    /**
     * @var array
     */
    private array $favouriteSiteIds;

    public function __construct($resource, array $favouriteSiteIds = [])
    {
        parent::__construct($resource);
        $this->favouriteSiteIds = $favouriteSiteIds;
    }

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array|Arrayable|JsonSerializable
     */
    public function toArray($request)
    {
        $this->resource = $this->resource
            ->through(fn($site) => $this->siteDetails($site));

        $result = parent::toArray($request);
        $result['favourite_site_ids'] = $this->favouriteSiteIds;

        return $result;
    }

    private function siteDetails(Tenant $site)
    {
        tenancy()->initialize($site);
        try {
            $icon = Settings::get('site-favicon') ?? $this->placeholder($site);
        } catch (\Exception $exception) {
            $icon = $this->placeholder($site);
        }
        tenancy()->end();
        return [
            'id' => $site->id,
            'name' => $site->name,
            'icon' => $icon,
            'is_suspended' => $site->is_suspended,
            'has_cloudflare' => $site->has_cloudflare,
            'is_live' => !empty($site->live_at),
            'primary_domain' => $site->domains->where('primary', 1)->first()?->domain,
            'domains' => $site->domains->pluck('domain'),
            'tier' => $site->tier,
            'user_limit' => TierHelper::userLimit($site->tier),
            'currency' => Currencies::getSymbol($site->currency ?? 'GBP'),
            'features' => $site->features->pluck('feature'),
            'is_favourite' => in_array($site->id, $this->favouriteSiteIds),
            'users' => $site->users->map(fn($user) => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'profile_photo_url' => $user->profile_photo_url,
                'role' => $user->pivot->role,
            ])
        ];
    }

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