<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminPasswordChanged
{
    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = auth('admin')->user();

        if (! $user instanceof User || ! $user->must_change_password) {
            return $next($request);
        }

        if ($this->isAllowedPasswordChangeRequest($request)) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'The default admin password must be changed before using the admin panel.',
            ], 423);
        }

        return redirect('/admin/change-password');
    }

    private function isAllowedPasswordChangeRequest(Request $request): bool
    {
        return $request->is('admin/change-password')
            || $request->is('admin/logout')
            || $request->is('admin/login')
            || $request->is('livewire/*');
    }
}
