<?php

namespace App\Services\EmailCampaign\Drivers;

use App\Models\EmailCampaign;
use App\Models\EmailCampaignRecipient;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;
use MailerLite\MailerLite;

class MailerLiteDriver extends AbstractEmailCampaignDriver
{
    protected function client(): MailerLite
    {
        $apiKey = (string) Setting::getValue('mailerlite_api_key', '');
        if ($apiKey === '') {
            throw new \RuntimeException('MailerLite not configured');
        }
        return new MailerLite(['api_key' => $apiKey]);
    }

    public function send(EmailCampaign $campaign, EmailCampaignRecipient $recipient): array
    {
        if ($campaign->remote_id) {
            return ['success' => true];
        }

        try {
            $client = $this->client();

            $listId = $campaign->list?->remote_id;
            if (! $listId) {
                return ['success' => false, 'error' => 'List has no MailerLite remote_id (sync first)'];
            }

            $createResp = $client->campaigns->create([
                'name' => $campaign->name,
                'language_id' => 1,
                'type' => 'regular',
                'emails' => [[
                    'subject' => $campaign->subject ?: $campaign->name,
                    'from_name' => $campaign->from_name ?: 'Demo',
                    'from' => $campaign->from_email ?: 'no-reply@procp.test',
                    'content' => (string) $campaign->content_html,
                ]],
                'groups' => [$listId],
            ]);

            $remoteId = $createResp['body']['data']['id'] ?? null;
            if (! $remoteId) {
                return ['success' => false, 'error' => 'MailerLite create returned no id'];
            }

            $client->campaigns->schedule($remoteId, [
                'delivery' => 'instant',
            ]);

            $campaign->update(['remote_id' => (string) $remoteId]);

            return ['success' => true];
        } catch (\Throwable $e) {
            Log::warning('MailerLiteDriver send failed', [
                'campaign_id' => $campaign->id,
                'error' => $e->getMessage(),
            ]);
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public function sendTest(EmailCampaign $campaign, string $email): array
    {
        // MailerLite doesn't have a clean "test send" without a campaign — fallback to local rendering
        return ['success' => false, 'error' => 'Test send not supported on MailerLite — use Local provider for test sends'];
    }

    public function supportsTracking(): bool
    {
        return true;
    }
}
