<?php

namespace App\Http\Middleware;

use App\Services\ApiTokenService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class AutoLoginViaRemember
{
    public function __construct(
        private readonly ApiTokenService $apiTokenService
    ) {}

    /**
     * 세션 만료 시 remember_token으로 자동 로그인
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 이미 인증된 경우 통과
        if (Auth::check()) {
            return $next($request);
        }

        // Remember Token으로 재인증 시도
        if (Auth::viaRemember()) {
            $user = Auth::user();

            // HQ 테넌트 소속 확인
            if (! $user->belongsToHQ()) {
                Auth::logout();
                Log::info('[AutoLoginViaRemember] Non-HQ user rejected', ['user_id' => $user->id]);

                return $next($request);
            }

            // 활성 상태 확인
            if (! $user->is_active) {
                Auth::logout();
                Log::info('[AutoLoginViaRemember] Inactive user rejected', ['user_id' => $user->id]);

                return $next($request);
            }

            // HQ 테넌트를 기본 선택
            $hqTenant = $user->getHQTenant();
            if ($hqTenant) {
                session(['selected_tenant_id' => $hqTenant->id]);

                // API 토큰 재발급
                $this->refreshApiToken($user->id, $hqTenant->id);
            }

            Log::info('[AutoLoginViaRemember] Auto login successful', ['user_id' => $user->id]);
        }

        return $next($request);
    }

    /**
     * API 토큰 재발급
     */
    private function refreshApiToken(int $userId, int $tenantId): void
    {
        try {
            $result = $this->apiTokenService->exchangeToken($userId, $tenantId);

            if ($result['success']) {
                $this->apiTokenService->storeTokenInSession(
                    $result['data']['access_token'],
                    $result['data']['expires_in']
                );
            }
        } catch (\Exception $e) {
            Log::warning('[AutoLoginViaRemember] API token refresh failed', [
                'user_id' => $userId,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
