<?php

namespace App\Actions\Fortify;

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

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, ProfileValidationRules;

    /**
     * Validate and create a newly registered user.
     *
     * New users are automatically assigned the 'user' role.
     * Curadores and Admins are promoted by existing admins.
     *
     * @param  array<string, string>  $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            ...$this->registrationProfileRules(),
            'password' => $this->passwordRules(),
        ])->validate();

        $avatarPath = null;
        if (isset($input['avatar']) && $input['avatar'] instanceof \Illuminate\Http\UploadedFile) {
            $avatarPath = $input['avatar']->store('avatars', 'public');
        }

        $user = User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
            'age' => $input['age'] ?? null,
            'gender' => $input['gender'] ?? null,
            'country' => $input['country'] ?? null,
            'entheogen_activity' => $input['entheogen_activity'] ?? null,
            'avatar' => $avatarPath,
        ]);

        // Assign default 'user' role to all newly registered users
        $user->assignRole('user');

        return $user;
    }
}
