<?php

namespace App\Http\Requests;

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

class AddSiteUserRequest extends FormRequest
{
    use CentralConnection;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check()
            && Auth::user()->hasRole(['mtc', 'Administrator'])
            && $this->doesNotExceedUserLimit();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    #[ArrayShape(['email' => "string[]", 'role' => "string[]"])] 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(tenant('id')) < TierHelper::userLimit(tenant('tier'));
    }
}
