<?php

namespace App\Http\Middleware;

use App\Models\Company;
use App\Support\Tenant;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Resuelve la empresa activa (tenant) del request a partir de:
 *  1) usuario autenticado con company_id (rutas privadas)
 *  2) parámetro {company} de la ruta (rutas públicas /empresa/{slug})
 *
 * El SuperAdmin nunca tiene tenant; opera sobre todas las empresas.
 */
class ResolveTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        $company = $this->resolveFromUser($request)
                ?? $this->resolveFromRoute($request);

        if ($company) {
            Tenant::set($company);
            // Bind global para que los componentes Blade puedan accederlo.
            app()->instance('current.tenant', $company);
            view()->share('currentTenant', $company);
        }

        try {
            return $next($request);
        } finally {
            Tenant::clear();
        }
    }

    protected function resolveFromUser(Request $request): ?Company
    {
        $user = $request->user();

        if (! $user || ! $user->company_id) {
            return null;
        }

        return Company::find($user->company_id);
    }

    protected function resolveFromRoute(Request $request): ?Company
    {
        $companyParam = $request->route('company');

        if (! $companyParam) {
            return null;
        }

        if ($companyParam instanceof Company) {
            return $companyParam;
        }

        return Company::where('slug', $companyParam)->first();
    }
}
