<?php

namespace App\Http\Middleware;

use App\Services\Auth\MobileTokenService;
use App\Services\Auth\MobileStudentResolver;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateMobileToken
{
    public function __construct(
        protected MobileTokenService $tokenService,
        protected MobileStudentResolver $studentResolver,
    ) {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $plainTextToken = $request->bearerToken();

        if (!$plainTextToken) {
            return $this->unauthorized('Token autentikasi dibutuhkan.');
        }

        $token = $this->tokenService->findValidToken($plainTextToken);

        if (!$token) {
            return $this->unauthorized('Token tidak valid atau sudah kedaluwarsa.');
        }

        // Siswa pemilik token (default)
        $tokenOwner = $this->studentResolver->findByAccountId($token->nouid);

        if (!$tokenOwner) {
            $token->delete();

            return $this->unauthorized('Akun tidak ditemukan.');
        }

        $this->tokenService->touch($token);

        // Cek apakah ada header X-Active-Student untuk switch anak
        $activeNis = $request->header('X-Active-Student');

        if ($activeNis && $activeNis !== $tokenOwner->nis) {
            $activeSiswa = $this->studentResolver->findSiblingByNis((string) $activeNis, $tokenOwner);

            if (!$activeSiswa) {
                return $this->forbidden('Siswa tidak terhubung ke akun ini.');
            }

            $siswa = $activeSiswa;
        } else {
            $siswa = $tokenOwner;
        }

        $request->attributes->set('auth_mobile_token', $token);
        $request->attributes->set('auth_account_id', $token->nouid);
        $request->attributes->set('auth_nouid', $siswa->indentitas?->nouid ?? $tokenOwner->indentitas?->nouid);
        $request->attributes->set('auth_siswa', $siswa);
        $request->attributes->set('auth_token_owner', $tokenOwner);
        $request->setUserResolver(fn () => $siswa);

        return $next($request);
    }

    protected function unauthorized(string $message): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => $message,
        ], 401);
    }

    protected function forbidden(string $message): JsonResponse
    {
        return response()->json([
            'success' => false,
            'message' => $message,
        ], 403);
    }
}
