<?php

namespace App\Services\Billing;

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

/**
 * Platform suite email (zero-config): channel=suite, no Bird customer API key.
 */
class PlatformEmailClient
{
    private ?string $lastError = null;

    private ?string $lastErrorCode = null;

    public function lastError(): ?string
    {
        return $this->lastError;
    }

    public function lastErrorCode(): ?string
    {
        return $this->lastErrorCode;
    }

    private function base(): string
    {
        return rtrim((string) config('smtp.platform_api_url', 'https://ladill.com/api/smtp'), '/');
    }

    private function token(): string
    {
        return (string) config('smtp.platform_api_key', '');
    }

    public function isConfigured(): bool
    {
        return $this->token() !== '';
    }

    public function messagingSettingsUrl(): string
    {
        return (string) config(
            'smtp.messaging_settings_url',
            'https://account.ladill.com/account/settings/messaging?reason=messaging_mailbox_required&from=suite',
        );
    }

    public function send(
        string $ownerPublicId,
        string $to,
        string $subject,
        string $html,
        ?string $text = null,
        ?string $fromName = null,
        ?string $idempotencyKey = null,
    ): bool {
        $this->lastError = null;
        $this->lastErrorCode = null;

        if (! $this->isConfigured()) {
            $this->lastError = 'Outbound email is not configured on this Care instance. Set SMTP_API_KEY_CARE.';

            return false;
        }

        $key = $idempotencyKey ?: ('care-email-'.Str::uuid());

        try {
            $res = Http::withToken($this->token())
                ->withHeaders(['Idempotency-Key' => $key])
                ->acceptJson()
                ->timeout(30)
                // from_name: caller should pass the clinic/org name for patient-facing
                // mail. Do not default to CARE_SMTP_FROM_NAME ("Ladill Care") — that is
                // product branding; suite From display must look like the customer.
                ->post($this->base().'/messages/send', array_filter([
                    'user' => $ownerPublicId,
                    'channel' => 'suite',
                    'from_name' => $fromName,
                    'to' => $to,
                    'subject' => $subject,
                    'html' => $html,
                    'text' => $text,
                    'reference' => $key,
                ], static fn ($v) => $v !== null && $v !== ''));

            if ($res->status() === 402) {
                $this->lastErrorCode = (string) ($res->json('error') ?: 'allowance_exceeded');
                $this->lastError = (string) ($res->json('error') ?: 'Email allowance exceeded. Upgrade Care Pro or top up your wallet.');
                Log::warning('Care suite email: allowance/balance', ['user' => $ownerPublicId]);

                return false;
            }

            if ($res->failed()) {
                $code = (string) ($res->json('error') ?: 'send_failed');
                $this->lastErrorCode = $code;
                if ($code === 'messaging_mailbox_required') {
                    $this->lastError = 'Set a Ladill mailbox in Account → Messaging: '.$this->messagingSettingsUrl();
                } else {
                    $this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The email could not be sent.');
                }
                Log::warning('Care suite email failed', ['status' => $res->status(), 'body' => $res->body()]);

                return false;
            }

            return (bool) ($res->json('success') ?? true);
        } catch (\Throwable $e) {
            $this->lastError = 'Could not reach the email service. Please try again.';
            Log::warning('Care suite email error', ['error' => $e->getMessage()]);

            return false;
        }
    }
}
