<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Support\ApiResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        // For API requests, return null to prevent redirection
        if ($request->expectsJson() || $request->is('api/*')) {
            return null;
        }

        // For non-API requests, redirect to home (or customize as needed)
        return route('home');
    }

    /**
     * Handle an unauthenticated user.
     *
     * @param  Request  $request
     * @return void
     *
     * @throws AuthenticationException
     */
    protected function unauthenticated($request, array $guards)
    {
        if ($request->expectsJson() || $request->is('api/*')) {
            abort(ApiResponse::response(message: 'برای دسترسی به این وبسرویس لاگین کنید', status: 421));
        }

        parent::unauthenticated($request, $guards);
    }
}
