<?php

namespace App\Actions\Fortify;

use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\Group;
use App\Models\User;
use Illuminate\Support\Facades\DB;
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(),
            'first_name' => ['nullable', 'string', 'max:255'],
            'last_name' => ['nullable', 'string', 'max:255'],
            'company' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:32'],
            'username' => ['nullable', 'string', 'max:255', 'unique:'.User::class],
            'password' => $this->passwordRules(),
        ])->validate();

        return DB::transaction(function () use ($input): User {
            $user = User::create([
                'name' => $input['name'],
                'first_name' => $input['first_name'] ?? null,
                'last_name' => $input['last_name'] ?? null,
                'company' => $input['company'] ?? null,
                'phone' => $input['phone'] ?? null,
                'username' => $input['username'] ?? null,
                'email' => $input['email'],
                'password' => $input['password'],
            ]);

            // Member baru otomatis bergabung grup `members` (RPD default_group).
            $membersGroup = Group::where('name', Group::MEMBERS)->value('id')
                ?? Group::firstOrCreate(['name' => Group::MEMBERS])->id;

            $user->groups()->attach($membersGroup);

            return $user;
        });
    }
}
