<?php

namespace App\Domains\Notification\Services;

use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Integration\Services\MailService;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\TicketPdfService;
use App\Domains\Ticket\Services\TicketPresentationResolver;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Throwable;

class NotificationMailService
{
    public function __construct(
        private readonly MailService $mailService,
        private readonly TicketPdfService $ticketPdfService,
    ) {}

    public function sendWelcome(int $userId, string $tenantCode): void
    {
        $this->sendLogged('welcome', [
            'user_id' => $userId,
            'tenant_code' => $tenantCode,
        ], function () use ($userId, $tenantCode): array {
            $tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
            $user = User::query()->findOrFail($userId);
            $brand = $tenant->websiteType ?? $tenant;

            $this->mailService
                ->forTenant($tenantCode)
                ->send(
                    $user->email,
                    "Bienvenido a {$brand->nombre}",
                    view('mail.notifications.welcome', compact('brand', 'user'))->render(),
                    $brand,
                );

            return [
                'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
            ];
        });
    }

    public function sendPasswordResetCode(
        int $attemptId,
        string $tenantCode,
        string $channel = PasswordResetRequested::CHANNEL_STOREFRONT,
    ): void {
        $context = [
            'attempt_id' => $attemptId,
            'tenant_code' => $tenantCode,
            'channel' => $channel,
        ];

        $this->sendLogged('password_reset', $context, function () use ($attemptId, $tenantCode, $channel, $context): ?array {
            $tenant = Tenant::query()
                ->with('websiteType')
                ->where('codigo', $tenantCode)
                ->firstOrFail();
            $attempt = ResetPasswordAttempt::query()
                ->with('user')
                ->findOrFail($attemptId);

            if ($attempt->status !== ResetPasswordAttempt::STATUS_PENDING) {
                $this->logSkipped('password_reset', array_merge($context, [
                    'reason' => 'attempt_not_pending',
                    'attempt_status' => $attempt->status,
                    'user_id' => $attempt->user_id,
                ]));

                return null;
            }

            $recoveryDomain = match ($channel) {
                PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
                PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
                default => $tenant->dominio,
            };
            $recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
                && $tenant->base_path !== '/'
                    ? $tenant->base_path
                    : '';
            $recoveryQuery = ['email' => $attempt->user->email];
            if (
                $channel === PasswordResetRequested::CHANNEL_SCANNER
                && $attempt->reason === ResetPasswordAttempt::REASON_STAFF_CREATED
            ) {
                $recoveryQuery['code'] = $attempt->codigo;
            }
            $recoveryUrl = $recoveryDomain === null
                ? null
                : 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
            $brand = $tenant->websiteType ?? $tenant;

            $this->mailService
                ->forTenant($tenantCode)
                ->send(
                    $attempt->user->email,
                    "Código para recuperar tu contraseña - {$brand->nombre}",
                    view('mail.notifications.password-reset', [
                        'attempt' => $attempt,
                        'recoveryUrl' => $recoveryUrl,
                        'brand' => $brand,
                    ])->render(),
                    $brand,
                );

            return [
                'user_id' => $attempt->user_id,
                'recovery_domain_available' => $recoveryDomain !== null,
            ];
        });
    }

    public function sendPurchaseConfirmed(int $purchaseId): void
    {
        $context = ['purchase_id' => $purchaseId];

        $this->sendLogged('purchase_confirmed', $context, function () use ($purchaseId, $context): ?array {
            $purchase = Purchase::query()
                ->with(['tenant', 'user', 'items'])
                ->find($purchaseId);

            if ($purchase === null) {
                $this->logSkipped('purchase_confirmed', array_merge($context, [
                    'reason' => 'purchase_not_found',
                    'missing_model' => Purchase::class,
                ]));

                return null;
            }

            /** @var Collection<int, Ticket> $tickets */
            $tickets = Ticket::query()
                ->where('source_purchase_id', $purchase->getKey())
                ->where('tenant_code', $purchase->tenant_codigo)
                ->with(TicketPresentationResolver::RELATIONS)
                ->get();
            $attachments = $tickets->isEmpty()
                ? []
                : [[
                    'data' => $this->ticketPdfService->contents($purchase->tenant, $tickets),
                    'name' => $this->ticketPdfService->filename($tickets),
                    'mime' => 'application/pdf',
                ]];

            $this->mailService
                ->forTenant($purchase->tenant_codigo)
                ->send(
                    $this->recipientFor($purchase),
                    "Compra confirmada - Compra #{$purchase->getKey()}",
                    view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
                    attachments: $attachments,
                );

            return [
                'tenant_code' => $purchase->tenant_codigo,
                'user_id' => $purchase->user_id,
                'purchase_status' => $purchase->status,
                'purchase_item_count' => $purchase->items->count(),
                'ticket_count' => $tickets->count(),
                'ticket_ids' => $tickets->modelKeys(),
            ];
        });
    }

    private function recipientFor(Purchase $purchase): string
    {
        return (string) ($purchase->email ?: $purchase->user?->email);
    }

    /**
     * @param  array<string, mixed>  $context
     * @param  Closure(): (array<string, mixed>|null)  $send
     */
    private function sendLogged(string $emailType, array $context, Closure $send): void
    {
        try {
            $resultContext = $send();

            if ($resultContext === null) {
                return;
            }

            Log::channel('emails')->info('Notification email sent.', array_merge($context, $resultContext, [
                'email_type' => $emailType,
                'mailer' => $this->mailService->mailerName(),
            ]));
        } catch (Throwable $exception) {
            Log::channel('emails')->error('Notification email delivery failed.', array_merge($context, [
                'email_type' => $emailType,
                'exception' => $exception,
            ]));

            throw $exception;
        }
    }

    /** @param array<string, mixed> $context */
    private function logSkipped(string $emailType, array $context): void
    {
        Log::channel('emails')->warning('Notification email skipped.', array_merge($context, [
            'email_type' => $emailType,
        ]));
    }
}
