<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Offers\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Maestro\Core\Http\Controllers\Controller;
use Maestro\Core\Modules\Offers\Http\Requests\RenameOfferTemplateRequest;
use Maestro\Core\Modules\Offers\Http\Resources\OfferResource;
use Maestro\Core\Modules\Offers\Models\Offer;

final class OfferTemplateController extends Controller
{
    public function updateName(RenameOfferTemplateRequest $request, Offer $offer): JsonResponse
    {
        abort_unless($request->user()?->can('offers.templates.manage'), 403);
        abort_unless($offer->is_template, 404);

        $validated = $request->validated();
        $offer->template_name = $validated['template_name'];
        $offer->save();

        return response()->json([
            'data' => new OfferResource($offer->fresh(['sections.rows', 'customer', 'contactPerson'])),
        ]);
    }
}
