<?php

namespace App\Jobs;

use App\Mail\CartRecoveryMail;
use App\Models\CheckoutSession;
use App\Models\Product;
use App\Services\TenantMailConfigService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class SendCheckoutSessionRecoveryEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;

    public int $backoff = 60;

    public function __construct(
        public int $checkoutSessionId,
        public string $stageKey
    ) {}

    public function handle(TenantMailConfigService $mailConfig): void
    {
        $session = CheckoutSession::with('product')->find($this->checkoutSessionId);
        if (! $session) {
            return;
        }

        // Revalida elegibilidade (idempotência)
        if ($session->order_id !== null) {
            return;
        }
        if (! in_array($session->step, [CheckoutSession::STEP_FORM_STARTED, CheckoutSession::STEP_FORM_FILLED], true)) {
            return;
        }
        $email = (string) ($session->email ?? '');
        if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return;
        }

        $product = $session->product;
        if (! $product) {
            return;
        }

        $config = $product->checkout_config ?? [];
        $recovery = is_array($config['cart_recovery_email'] ?? null) ? $config['cart_recovery_email'] : [];
        if (empty($recovery['enabled'])) {
            return;
        }

        $stages = is_array($recovery['stages'] ?? null) ? $recovery['stages'] : [];
        $stage = is_array($stages[$this->stageKey] ?? null) ? $stages[$this->stageKey] : null;
        if (! $stage) {
            return;
        }

        $subjectTpl = (string) ($stage['subject'] ?? '');
        $bodyHtmlTpl = (string) ($stage['body_html'] ?? '');
        $bodyTextTpl = (string) ($stage['body_text'] ?? '');
        if (trim($subjectTpl) === '' || (trim($bodyTextTpl) === '' && trim($bodyHtmlTpl) === '')) {
            return;
        }

        $checkoutUrl = $this->buildCheckoutUrlForSession($session, $product);
        $name = trim((string) ($session->name ?? ''));
        $customerName = $name !== '' ? $name : (explode('@', $email)[0] ?? 'Cliente');

        $replace = [
            '{nome_cliente}' => $customerName,
            '{email_cliente}' => $email,
            '{nome_produto}' => (string) ($product->name ?? 'Produto'),
            '{valor}' => $this->formatBrl((float) ($product->price ?? 0)),
            '{link_checkout}' => $checkoutUrl,
        ];

        $subject = str_replace(array_keys($replace), array_values($replace), $subjectTpl);
        if (trim($bodyTextTpl) !== '') {
            $text = str_replace(array_keys($replace), array_values($replace), $bodyTextTpl);
            $body = $this->wrapTextInPrettyHtml($text, $checkoutUrl);
        } else {
            $body = str_replace(array_keys($replace), array_values($replace), $bodyHtmlTpl);
        }

        try {
            $mailConfig->applyMailerConfigForTenant($session->tenant_id ?? $product->tenant_id, [], null);
            Mail::purge('smtp');
            Mail::mailer('smtp')->to($email)->send(new CartRecoveryMail($subject, $body));
        } catch (\Throwable $e) {
            Log::warning('SendCheckoutSessionRecoveryEmailJob: falha ao enviar', [
                'checkout_session_id' => $session->id,
                'tenant_id' => $session->tenant_id,
                'stage' => $this->stageKey,
                'message' => $e->getMessage(),
            ]);
        }
    }

    private function buildCheckoutUrlForSession(CheckoutSession $session, Product $product): string
    {
        $slug = trim((string) ($session->checkout_slug ?: $product->checkout_slug));
        $base = url('/c/' . $slug);
        $params = array_filter([
            'email' => $session->email,
            'name' => $session->name,
        ], fn ($v) => is_string($v) && trim($v) !== '');

        return $params ? ($base . '?' . http_build_query($params)) : $base;
    }

    private function formatBrl(float $value): string
    {
        return 'R$ ' . number_format($value, 2, ',', '.');
    }

    private function wrapTextInPrettyHtml(string $text, string $checkoutUrl): string
    {
        $safe = htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        $safe = str_replace(["\r\n", "\r"], "\n", $safe);
        $paragraphs = array_values(array_filter(array_map('trim', explode("\n\n", $safe)), fn ($p) => $p !== ''));
        $htmlParagraphs = '';
        foreach ($paragraphs as $p) {
            $p = nl2br($p, false);
            $htmlParagraphs .= '<p style="margin:0 0 16px;font-size:15px;line-height:1.6;color:#334155;">' . $p . '</p>';
        }

        $urlSafe = htmlspecialchars($checkoutUrl, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        $buttonLabel = Str::contains($checkoutUrl, '/c/') ? 'Continuar compra' : 'Acessar link';

        return '<table width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;margin:0 auto;font-family:\'Segoe UI\',Tahoma,sans-serif;background:#f8fafc;padding:32px 24px;"><tr><td style="background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.08);"><table width="100%" cellpadding="0" cellspacing="0"><tr><td style="padding:28px 32px;">'
            . $htmlParagraphs
            . '<p style="margin:0 0 22px;text-align:center;"><a href="' . $urlSafe . '" style="display:inline-block;padding:14px 28px;background:#0ea5e9;color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;border-radius:10px;">' . htmlspecialchars($buttonLabel, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</a></p>'
            . '<p style="margin:0 0 18px;font-size:13px;line-height:1.5;color:#64748b;">Se o botão não abrir, copie e cole no navegador:<br/><a href="' . $urlSafe . '" style="color:#0ea5e9;word-break:break-all;">' . $urlSafe . '</a></p>'
            . '<p style="margin:0;font-size:13px;line-height:1.6;color:#64748b;">Se tiver qualquer dúvida, responda este e-mail.</p>'
            . '</td></tr></table></td></tr></table>';
    }
}

