<?php

namespace App\Services\Messaging;

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

class CustomerEmailClient
{
    private ?string $lastError = null;

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

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

    /** @return array{ok: bool, data?: array<string, mixed>, error?: string, status?: int} */
    public function me(string $apiKey): array
    {
        try {
            $res = Http::withToken($apiKey)->acceptJson()->timeout(15)
                ->get($this->base().'/me');

            if ($res->status() === 401) {
                $platformError = trim((string) ($res->json('error') ?: ''));

                return [
                    'ok' => false,
                    'error' => $platformError !== ''
                        ? $platformError
                        : 'Invalid Bird API key. Use the HTTP API key from bird.ladill.com (starts with lsk_live_).',
                    'status' => 401,
                ];
            }

            if ($res->failed()) {
                return [
                    'ok' => false,
                    'error' => (string) ($res->json('error') ?: 'Could not validate Bird credentials.'),
                    'status' => $res->status(),
                ];
            }

            return ['ok' => true, 'data' => $res->json() ?? [], 'status' => $res->status()];
        } catch (\Throwable $e) {
            Log::warning('Customer Bird meta request failed', ['error' => $e->getMessage()]);

            return ['ok' => false, 'error' => 'Could not reach Ladill Bird. Please try again.'];
        }
    }

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

        try {
            $res = Http::withToken($apiKey)->acceptJson()->timeout(30)
                ->post($this->base().'/send', array_filter([
                    'from' => $from,
                    'from_name' => $fromName,
                    'to' => [$to],
                    'subject' => $subject,
                    'html' => $html,
                    'text' => $text,
                ], fn ($value) => $value !== null && $value !== ''));

            if ($res->status() === 402) {
                $this->lastError = (string) ($res->json('error') ?: 'Insufficient Bird email credits. Top up Bird and try again.');

                return false;
            }

            if ($res->failed()) {
                $this->lastError = (string) ($res->json('error') ?: $res->json('message') ?: 'The email could not be sent.');
                Log::warning('Customer email send failed', ['status' => $res->status()]);

                return false;
            }

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

            return false;
        }
    }
}
