<?php

namespace App\Actions\Fortify;

use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\User;
use App\Models\Vrm\Role;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, ProfileValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array<string, string>  $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            ...$this->profileRules(requirePhone: true),
            'password' => $this->passwordRules(),
        ])->validate();

        $this_user = User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'phone' => $this->normalizePhone($input['phone'] ?? null),
            'password' => $input['password'],
        ]);

        $memberRole = Role::query()->firstOrCreate(
            ['slug' => 'member'],
            [
                'name' => 'Member',
                'module' => 'contribution',
                'authority' => 'member',
                'is_active' => 1,
                'description' => 'Member',
            ]
        );

        $this_user->roles()->syncWithoutDetaching([$memberRole->id]);

        return $this_user;
    }
}
