<?php

namespace App\Master\Http\Requests;

use App\Master\SiteManager;
use App\TierHelper;
use Illuminate\Support\Facades\Auth;
use JetBrains\PhpStorm\ArrayShape;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class InviteUserToSiteRequest extends SiteRequest
{
    use CentralConnection;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    #[\Override]
    public function authorize()
    {
        return Auth::check()
            && Auth::user()->hasRole('mtc')
            && $this->doesNotExceedUserLimit();
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    #[ArrayShape(['email' => "string[]", 'role' => "string[]"])]
    #[\Override] public function rules()
    {
        $global = $this->getConnectionName();
        return [
            'email' => [
                'required',
                'email',
            ],
            'role' => [
                'required',
                "exists:$global.roles,name",
            ]
        ];
    }

    /**
     * Check there is enough spaces on tier to create user
     *
     * @return bool
     */
    private function doesNotExceedUserLimit(): bool
    {
        return new SiteManager()->getSiteUserCount($this->site->id) < TierHelper::userLimit($this->site->tier);
    }
}
