<?php

namespace App\Http\Controllers;

use App\Http\Requests\LeadExportTemplateRequest;
use App\Http\Requests\StoreLeadExportTemplate;
use App\Http\Requests\UpdateLeadExportTemplate;
use App\Http\Resources\LeadExportTemplateList;
use App\Http\Resources\LeadExportTemplateResource;
use App\Models\LeadExportTemplate;

/**
 * System-level CRUD for CRM lead export templates (central connection). Mirrors
 * ExportMapTemplateController / NotificationTemplateController: a published template
 * can then be applied to a site's lead export.
 */
class LeadExportTemplateController extends Controller
{
    public function index(LeadExportTemplateRequest $request): LeadExportTemplateList
    {
        return new LeadExportTemplateList(LeadExportTemplate::query()->latest()->paginate());
    }

    public function show(
        LeadExportTemplateRequest $request,
        LeadExportTemplate $leadExportTemplate
    ): LeadExportTemplateResource {
        return new LeadExportTemplateResource($leadExportTemplate);
    }

    public function store(StoreLeadExportTemplate $request): LeadExportTemplateResource
    {
        $leadExportTemplate = LeadExportTemplate::query()->create([
            'title' => $request->input('title'),
            'type' => $request->input('type', 'lead'),
            'is_published' => false,
        ]);

        return new LeadExportTemplateResource($leadExportTemplate);
    }

    public function update(
        UpdateLeadExportTemplate $request,
        LeadExportTemplate $leadExportTemplate
    ): LeadExportTemplateResource {
        $leadExportTemplate->update($request->validated());

        return new LeadExportTemplateResource($leadExportTemplate);
    }

    public function destroy(
        LeadExportTemplateRequest $request,
        LeadExportTemplate $leadExportTemplate
    ): LeadExportTemplateList {
        $leadExportTemplate->delete();

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