<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserConsent;
use App\Notifications\Auth\LegalConsentConfirmation;
use App\Services\Auth\PasswordPolicyService;
use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    public function __construct(
        protected SystemConfigService $systemConfig
    ) {}

    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', PasswordPolicyService::getRules()],
            'agree_tos_pdp' => ['required', 'accepted'],
            'marketing_consent' => ['nullable'], // Fix: removed 'boolean' to handle "on" value from checkbox
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password, // Rely on 'hashed' cast in User model
        ]);

        // Record to history and set initial password_changed_at
        PasswordPolicyService::recordPasswordChange($user, $user->password);

        // DEFAULT ROLE = User
        $user->assignRole('User');

        // RECORD CONSENT AUDIT LOGS (UU PDP COMPLIANCE)
        $this->recordUserConsents($user, $request);

        // TRIGGER CONFIRMATION EMAIL (Wrapped in try-catch to prevent registration failure on mail errors)
        try {
            $user->notify(new LegalConsentConfirmation([
                'tos' => $this->systemConfig->get('tos_document_version', 1),
                'privacy' => $this->systemConfig->get('pdp_document_version', 1),
            ]));
        } catch (\Exception $e) {
            Log::error('Failed to send registration consent email: '.$e->getMessage());
        }

        event(new Registered($user));

        Auth::login($user);

        return redirect(route('dashboard', absolute: false));
    }

    /**
     * Record the audit log for user consents.
     */
    protected function recordUserConsents(User $user, Request $request): void
    {
        $ip = $request->ip();
        $ua = $request->userAgent();

        // 1. TOS & PDP (Mandatory)
        UserConsent::create([
            'user_id' => $user->id,
            'consent_type' => 'tos',
            'version_id' => (int) $this->systemConfig->get('tos_document_version', 1),
            'ip_address' => $ip,
            'user_agent' => $ua,
        ]);

        UserConsent::create([
            'user_id' => $user->id,
            'consent_type' => 'privacy',
            'version_id' => (int) $this->systemConfig->get('pdp_document_version', 1),
            'ip_address' => $ip,
            'user_agent' => $ua,
        ]);

        // 2. Marketing (Optional)
        if ($request->boolean('marketing_consent')) {
            UserConsent::create([
                'user_id' => $user->id,
                'consent_type' => 'marketing',
                'version_id' => 1,
                'ip_address' => $ip,
                'user_agent' => $ua,
            ]);
        }
    }
}
