<?php

namespace App\Actions\Fortify;

use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Laravel\Fortify\Contracts\CreatesNewUsers;

class CreateNewUser implements CreatesNewUsers
{
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'min:2', 'max:100'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique(User::class)],
            'password' => ['required', 'string', 'confirmed', Password::min(10)->mixedCase()->numbers()->symbols()],
            'terms' => ['accepted'],
        ])->validate();

        // FIX-120: Validate referral code exists if provided
        $referredBy = $input['referral_code'] ?? null;
        if ($referredBy) {
            $referrerExists = User::where('referral_code', strtoupper(trim($referredBy)))
                ->where('status', 'active')
                ->exists();
            if (!$referrerExists) {
                $referredBy = null; // Silently ignore invalid referral codes
            }
        }

        $user = User::create([
            'name' => $input['name'],
            // FIX-011: Normalize email to lowercase
            'email' => strtolower($input['email']),
            'password' => $input['password'],
            // Increased from 8 to 16 chars for better entropy
            'referral_code' => strtoupper(\Illuminate\Support\Str::random(16)),
            'referred_by' => $referredBy,
        ]);

        try {
            $user->notify(new \App\Notifications\WelcomeNotification());
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::warning('Welcome email skipped: ' . $e->getMessage());
        }

        return $user;
    }
}
