<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreNewsletterRequest;
use App\Services\MailchimpService;
use Illuminate\Http\JsonResponse;

class NewsletterController extends Controller
{
    public function store(StoreNewsletterRequest $request, MailchimpService $mailchimp, string $locale): JsonResponse
    {
        $subscribed = $mailchimp->subscribe($request->validated('email'), $locale);

        if (! $subscribed) {
            $message = $locale === 'en'
                ? 'Something went wrong. Please try again later.'
                : "Une erreur est survenue. Veuillez réessayer plus tard.";

            return response()->json(['message' => $message], 502);
        }

        $message = $locale === 'en'
            ? 'Thanks for subscribing!'
            : 'Merci pour votre inscription !';

        return response()->json(['message' => $message]);
    }
}
