<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\Newsletter\StoreNewsletterRequest;
use App\Http\Resources\NewsletterResource;
use App\Models\Newsletter;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Support\Facades\DB;

class NewsletterController extends Controller
{
    public function store(StoreNewsletterRequest $request)
    {
        try {
            DB::beginTransaction();

            $newsletter = Newsletter::create($request->validated());

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::created(
            new NewsletterResource($newsletter),
            'عضویت در خبرنامه با موفقیت ثبت شد.'
        );
    }
}
