<?php

namespace App\Http\Controllers;

use App\Http\Requests\NotificationTemplateRequest;
use App\Http\Requests\StoreNotificationTemplate;
use App\Http\Requests\UpdateNotificationTemplate;
use App\Http\Resources\NotificationTemplateList;
use App\Http\Resources\NotificationTemplateResource;
use App\Models\NotificationTemplate;

/**
 * System-level CRUD for inbound notification templates (central connection). Mirrors
 * ExportMapTemplateController: a published template can then be applied to a site's
 * notification map.
 */
class NotificationTemplateController extends Controller
{
    public function index(NotificationTemplateRequest $request): NotificationTemplateList
    {
        return new NotificationTemplateList(NotificationTemplate::query()->latest()->paginate());
    }

    public function show(
        NotificationTemplateRequest $request,
        NotificationTemplate $notificationTemplate
    ): NotificationTemplateResource {
        return new NotificationTemplateResource($notificationTemplate);
    }

    public function store(StoreNotificationTemplate $request): NotificationTemplateResource
    {
        $notificationTemplate = NotificationTemplate::query()->create([
            'title' => $request->input('title'),
            'type' => $request->input('type', 'vehicle'),
            'is_published' => false,
        ]);

        return new NotificationTemplateResource($notificationTemplate);
    }

    public function update(
        UpdateNotificationTemplate $request,
        NotificationTemplate $notificationTemplate
    ): NotificationTemplateResource {
        $notificationTemplate->update($request->validated());

        return new NotificationTemplateResource($notificationTemplate);
    }

    public function destroy(
        NotificationTemplateRequest $request,
        NotificationTemplate $notificationTemplate
    ): NotificationTemplateList {
        $notificationTemplate->delete();

        return $this->index($request);
    }
}
