<?php

namespace App\Http\Middleware;

use App\TemplateRepository;
use Closure;
use Illuminate\Http\Request;
use Mtc\ContentManager\Contracts\Template as TemplateContract;

class EnforceTemplateLock
{
    public function __construct(private TemplateRepository $repository)
    {
    }

    public function handle(Request $request, Closure $next)
    {
        if (!in_array($request->method(), ['PUT', 'PATCH', 'DELETE'], true)) {
            return $next($request);
        }

        $template = $request->route('template');

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

        return $next($request);
    }
}
