<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class MailchimpService
{
    /**
     * Ajoute (ou met à jour) un contact dans l'audience Mailchimp configurée.
     * Retourne true si l'abonné est enregistré (déjà présent inclus).
     */
    public function subscribe(string $email, string $locale): bool
    {
        $apiKey = config('services.mailchimp.key');
        $audienceId = config('services.mailchimp.audience_id');
        $datacenter = Str::after($apiKey, '-');

        $subscriberHash = md5(strtolower($email));

        $response = Http::withBasicAuth('obvious-way', $apiKey)
            ->put("https://{$datacenter}.api.mailchimp.com/3.0/lists/{$audienceId}/members/{$subscriberHash}", [
                'email_address' => $email,
                'status_if_new' => 'subscribed',
                'language' => $locale,
            ]);

        return $response->successful();
    }
}
