<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\ReportDeliveryRepository;

final class InstitutionDeliveryService
{
    public function sendReport(array $report, array $institution, array $document, string $channel = 'email'): array
    {
        $channel = $channel === 'edelivery' ? 'edelivery' : 'email';
        $subject = 'Сигнал ' . ($report['tracking_number'] ?? '') . ' - ' . ($report['title'] ?? 'CiviGO.eu');

        if ($channel === 'edelivery') {
            return $this->prepareSecureDelivery($report, $institution, $document, $subject);
        }

        return $this->sendByEmail($report, $institution, $document, $subject);
    }

    private function sendByEmail(array $report, array $institution, array $document, string $subject): array
    {
        $recipient = (string) ($institution['email'] ?? '');

        if ($recipient === '') {
            $delivery = [
                'report_id' => (int) $report['id'],
                'channel' => 'email',
                'recipient_name' => $institution['name'] ?? null,
                'recipient_email' => null,
                'subject' => $subject,
                'delivery_status' => 'needs_manual_channel',
                'provider_status' => 'missing_recipient_email',
                'message_id' => null,
                'sent_at' => null,
                'evidence' => [
                    'reason' => 'Институцията няма въведен email. Използвайте ССЕВ или електронния портал.',
                    'portal' => $institution['portal'] ?? null,
                    'edelivery' => config('delivery.edelivery_base_url'),
                ],
            ];

            return (new ReportDeliveryRepository())->create($delivery);
        }

        $mailerResult = (new MailerService())->send(
            $recipient,
            $subject,
            '<pre style="font:14px/1.6 system-ui, sans-serif;white-space:pre-wrap">' . e($document['text']) . '</pre>'
        );

        $delivery = [
            'report_id' => (int) $report['id'],
            'channel' => 'email',
            'recipient_name' => $institution['name'] ?? null,
            'recipient_email' => $recipient,
            'subject' => $subject,
            'delivery_status' => $mailerResult['ok'] ? 'sent_to_smtp' : 'failed',
            'provider_status' => $mailerResult['status'],
            'message_id' => $mailerResult['message_id'],
            'sent_at' => $mailerResult['sent_at'],
            'evidence' => [
                'smtp_accepted' => $mailerResult['ok'],
                'message_id' => $mailerResult['message_id'],
                'return_path' => config('mail.return_path'),
                'note' => 'SMTP приемането доказва изпращане към пощенската инфраструктура, но не доказва прочитане от служител.',
            ],
        ];

        return (new ReportDeliveryRepository())->create($delivery);
    }

    private function prepareSecureDelivery(array $report, array $institution, array $document, string $subject): array
    {
        $delivery = [
            'report_id' => (int) $report['id'],
            'channel' => 'edelivery',
            'recipient_name' => $institution['name'] ?? null,
            'recipient_email' => $institution['email'] ?? null,
            'subject' => $subject,
            'delivery_status' => 'manual_secure_delivery_required',
            'provider_status' => 'ready_for_ssev_or_portal',
            'message_id' => null,
            'sent_at' => null,
            'evidence' => [
                'portal' => $institution['portal'] ?? null,
                'edelivery' => config('delivery.edelivery_base_url'),
                'document_text_sha256' => hash('sha256', $document['text']),
                'next_step' => 'Потребителят или оператор трябва да подаде документа през ССЕВ/официалния портал и да въведе входящ номер.',
            ],
        ];

        return (new ReportDeliveryRepository())->create($delivery);
    }
}
