<?php

namespace Modules\Auth\Actions\Fortify;

use App\Traits\NotifiesAdmins;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Modules\Auth\Entities\User;
use Modules\Role\Entities\Role;
use Modules\User\Notifications\UserActivationNotification;
use Exception;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, NotifiesAdmins;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array<string, string>  $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'ic_number' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:8'],
        ])->validate();

        $user = User::create([
            'name' => $input['name'],
            'uuid' => Str::uuid(),
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
            'ic_number' => $input['ic_number'],
            'status' => 'pending',
        ]);

        // Assign role using Spatie permissions
        $role = Role::where('name', 'Anggota')->first();
        if ($role) {
            $user->assignRole($role);
        }

        return $user;
    }
}
