<?php

namespace App\Http\Middleware;

use App\GlobalContentRepository;
use Closure;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\GlobalContent;

class EnforceGlobalContentRestriction
{
    public function __construct(private GlobalContentRepository $repository)
    {
    }

    /**
     * Guard the superadmin-only restriction for global content. Non-MTC users
     * may not read, modify, delete or copy a flagged entry (403), nor set the
     * flag themselves when creating/updating content (the value is forced off).
     * The list route hides flagged entries via the query scope instead.
     */
    public function handle(Request $request, Closure $next)
    {
        $isMtc = $request->user()?->hasRole('mtc') === true;

        // apiResource routes pass a raw id ({global_element}); the copy route is
        // route-model bound ({element}), so it may already be a model instance.
        $target = $request->route('global_element') ?? $request->route('element');

        if ($target !== null) {
            $content = $target instanceof GlobalContent
                ? $target
                : GlobalContent::query()->find($target);

            if ($content instanceof GlobalContent
                && !$this->repository->userCanModify($content, $request->user())) {
                return response([
                    'message' => __('validation.not_allowed_to_modify_global_content'),
                ], 403);
            }
        }

        // Only MTC users may set the flag; force it off on writes for everyone else.
        if (!$isMtc && in_array($request->method(), ['POST', 'PUT', 'PATCH'], true)) {
            $request->merge(['superadmin_only' => false]);
        }

        return $next($request);
    }
}
