<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class CheckApiToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $header = $request->header('Authorization') ?: $request->bearerToken();

        if (! $header) {
            return response()->json(['success' => false, 'message' => 'Unauthorized: No token provided'], 401);
        }

        $token = preg_replace('/^Bearer\s+/i', '', $header);

        $tokenRecord = DB::table('api_tokens')
            ->where('token', $token)
            ->where('expires_at', '>', now())
            ->first();

        if (! $tokenRecord) {
            return response()->json(['success' => false, 'message' => 'Unauthorized: Invalid token'], 401);
        }

        // Log the user in for this request
        $user = User::find($tokenRecord->user_id);
        if ($user) {
            Auth::setUser($user);
            $request->merge(['user' => $user]); // Optional: make user available in request
        } else {
             return response()->json(['success' => false, 'message' => 'Unauthorized: User not found'], 401);
        }

        return $next($request);
    }
}
