<?php

namespace Modules\VetOneDemo\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

/**
 * Soft-locks a demo tenant once its 48-hour window elapses: marks the business
 * expired, logs the user out and redirects to the "contact TPS" landing.
 *
 * Pushed onto the 'web' group by the service provider, so it sees every web
 * request — but it is a cheap no-op unless the request is authenticated AND the
 * user's business is a demo tenant (demo_expires_at IS NOT NULL). The VetOne
 * register / onboarding / expired routes are exempt to avoid redirect loops.
 */
class EnsureDemoActive
{
    public function handle(Request $request, Closure $next)
    {
        // Guests (register/login pages, PWAs, public brand API) are never demo-locked here.
        if (! Auth::check()) {
            return $next($request);
        }

        // Never lock the VetOne demo pages themselves (register, onboarding, expired landing).
        if ($request->routeIs('vetone.*')) {
            return $next($request);
        }

        $businessId = Auth::user()->business_id ?? null;
        if (! $businessId) {
            return $next($request);
        }

        // One lightweight indexed lookup. Only the two lifecycle columns.
        $biz = DB::table('business')
            ->where('id', $businessId)
            ->first(['demo_expires_at', 'demo_status']);

        // Not a demo tenant → no-op.
        if (! $biz || $biz->demo_expires_at === null) {
            return $next($request);
        }

        if (Carbon::parse($biz->demo_expires_at)->isFuture()) {
            return $next($request);
        }

        // Expired: flip status once, then log out and send to the TPS landing.
        if ($biz->demo_status !== 'expired') {
            DB::table('business')->where('id', $businessId)->update(['demo_status' => 'expired']);
        }

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('vetone.demo_expired');
    }
}
