<?php

namespace App\Services\Core\Auth;

use App\Mail\Core\User\UserCreateMail;
use App\Models\Core\Auth\User;
use App\Repositories\Core\Status\StatusRepository;
use App\Services\Core\BaseService;
use App\Services\Core\Setting\DeliverySettingService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class UserCreateService extends BaseService
{
    protected UserInvitationService $userService;
    public function __construct(UserInvitationService $userService)
    {
        $this->userService = $userService;
    }

    public function validateMailSettings()
    {
        throw_if(
            !count(resolve(DeliverySettingService::class)->getCachedMailSettings()),
            ValidationException::withMessages([
                'email' => [__t('no_delivery_settings_found')]
            ])
        );

        return $this;
    }

    public function create()
    {
        $password = Str::random(8);
        /**@var User $user */
        $user = $this->userService
            ->create(
                $this->getAttribute('email'),
                array_merge(
                    $this->getAttributes(['first_name', 'last_name']),
                    [
                        'status_id' => resolve(StatusRepository::class)->userActive(),
                        'invitation_token' => '',
                        'password' => Hash::make($password)
                    ]
                )
            )
            ->assignRoles($this->getAttribute('roles'))
            ->getModel();

        $user->tempPass= $password;
        $this->createUserMail($user);

        return $user;
    }

    public function createUserMail(User $user)
    {
        Mail::to($user)
            ->locale(session()->get('locale') ?: settings('language') ?: "en")
            ->send((new UserCreateMail($user)));

        return $this;
    }
}