<?php

namespace App\Http\Controllers\Auth;

use App\Enums\UserStatus;
use App\Http\Controllers\Controller;
use App\Models\Applicant;
use App\Models\User;
use App\Services\AuditLogger;
use Illuminate\Auth\Events\Registered;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class RegisterController extends Controller
{
    public function __construct(protected AuditLogger $audit) {}

    public function show(): View
    {
        return view('auth.register');
    }

    /** Applicant self-registration (PRD 11). */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'middle_name' => ['nullable', 'string', 'max:100'],
            'last_name' => ['required', 'string', 'max:100'],
            'email' => ['required', 'string', 'email:rfc', 'max:190', 'unique:users,email'],
            'phone' => ['required', 'string', 'max:30', 'regex:/^[0-9+\-\s()]{7,30}$/'],
            'password' => ['required', 'confirmed', Password::min(8)->letters()->numbers()],
            'terms' => ['accepted'],
        ], [
            'terms.accepted' => 'Please accept the terms to create your account.',
            'phone.regex' => 'Enter a valid phone number, for example 0771 234 567.',
        ]);

        $user = DB::transaction(function () use ($data) {
            $user = User::create([
                'name' => trim("{$data['first_name']} {$data['last_name']}"),
                'email' => strtolower($data['email']),
                'phone' => $data['phone'],
                'password' => Hash::make($data['password']),
            ]);

            $user->forceFill(['status' => UserStatus::Active])->save();

            Applicant::create([
                'user_id' => $user->id,
                'first_name' => $data['first_name'],
                'middle_name' => $data['middle_name'] ?? null,
                'last_name' => $data['last_name'],
                'phone' => $data['phone'],
                'country' => 'Uganda',
            ]);

            return $user;
        });

        event(new Registered($user));

        Auth::login($user);

        $this->audit->log('user.registered', $user, [], ['email' => $user->email]);

        return redirect()->route('verification.notice')
            ->with('status', 'Your account has been created. Please verify your email address to continue.');
    }
}
