<?php

namespace App\Http\Middleware;

use App\Models\Dealer;
use App\Models\PasswordChangeToken;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

/**
 * Safety net: if an authenticated user still has force_password_change = true (e.g. old session),
 * log them out and send to login. Primary flow is handled at login (redirect to first-login set-password).
 */
class ForcePasswordChange
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if (! $user) {
            return $next($request);
        }

        if (! $user->force_password_change) {
            return $next($request);
        }

        // Create a fresh first-login password token and send the user directly
        // to the first-login set-password screen, instead of asking them to log in again.
        $token = Str::random(64);

        PasswordChangeToken::create([
            'user_id' => $user->id,
            'token_hash' => hash('sha256', $token),
            'expires_at' => now()->addMinutes(30),
        ]);

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('first-login.password.show', ['token' => $token])
            ->with('status', 'Set a new password to continue.');
    }

    private function dealerLoginRoute(Request $request, ?User $user = null): string
    {
        $codeFromRoute = $request->route('code');
        if (is_string($codeFromRoute) && $codeFromRoute !== '') {
            return route('dealer.login.show', ['code' => $codeFromRoute]);
        }

        if ($user && $user->dealer_id) {
            $dealerCode = Dealer::query()
                ->where('id', $user->dealer_id)
                ->value('code');

            if (is_string($dealerCode) && $dealerCode !== '') {
                return route('dealer.login.show', ['code' => $dealerCode]);
            }
        }

        return route('login');
    }
}

