<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Runs after ResolveTenant. When a company has been put into read-only
 * status (expired or cancelled subscription, or a manual suspend from the
 * SaaS control panel), its users can still log in and view everything —
 * this only steps in front of requests that would create, change, or
 * delete something.
 *
 * Login/logout are exempt on purpose: "read-only" means you can still get
 * in and look around, not that the account is locked out entirely.
 */
class EnforceCompanyReadOnly
{
    private const WRITE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];

    private const EXEMPT_NAME_FRAGMENTS = ['login', 'authenticate', 'logout'];

    public function handle(Request $request, Closure $next): Response
    {
        $company = currentCompany();

        if (!$company || !$company->isReadOnly() || !in_array($request->method(), self::WRITE_METHODS, true)) {
            return $next($request);
        }

        $routeName = $request->route()?->getName() ?? '';

        foreach (self::EXEMPT_NAME_FRAGMENTS as $fragment) {
            if (str_contains($routeName, $fragment)) {
                return $next($request);
            }
        }

        $message = __('This account is read-only right now — contact support to reactivate it before making changes.');

        if ($request->expectsJson()) {
            return response()->json(['message' => $message], 403);
        }

        return back()->with('error', $message);
    }
}
