<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Restricts Trades role users to only allowed routes.
 * Trades can only access: dashboard, profile, timesheet, staff invoices,
 * and their assigned jobs list/detail.
 *
 * Appended to the `web` middleware group in bootstrap/app.php.
 */
class TradesAccessMiddleware
{
    private const ALLOWED_ROUTES = [
        'login',
        'login.post',
        'logout',
        'dashboard',
        'profile.index',
        'profile.update',
        'profile.password',
        'timesheet.index',
        'timesheet.start',
        'timesheet.stop',
        'timesheet.destroy',
        'staff-invoices.index',
        'staff-invoices.show',
        'staff-invoices.request-approval',
        'notifications.index',
        'notifications.mark-read',
        'notifications.mark-all-read',
        'jobs.index',
        'jobs.show',
        'search',
    ];

    public function handle(Request $request, Closure $next): mixed
    {
        $user = $request->user();

        if (! $user || $user->role?->name !== 'trades') {
            return $next($request);
        }

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

        if ($routeName && ! in_array($routeName, self::ALLOWED_ROUTES, true)) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Access restricted for Trades role.'], 403);
            }
            abort(403, 'Access restricted. Your account can only view assigned jobs and timesheets.');
        }

        return $next($request);
    }
}
