<?php

namespace App\Http\Middleware;

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

class CompanyScope
{
    public function handle(Request $request, Closure $next, string $model = 'company_id'): Response
    {
        $user = $request->user();

        if (!$user) {
            return response()->json(['message' => 'Unauthorized'], 401);
        }

        if ($user->isSuperAdmin()) {
            return $next($request);
        }

        // Apply company_id scope to all queries
        $request->attributes->set('company_scope', $user->company_id);

        // For requests with explicit company_id in params, validate it matches user's company
        if ($request->has('company_id') && $request->company_id != $user->company_id) {
            return response()->json(['message' => 'Unauthorized access to this company'], 403);
        }

        return $next($request);
    }
}
