<?php

namespace App\Services\Communication;

use App\Services\EmailService;

class CommunicationSendService
{
    private EmailService $mailer;
    private CommunicationLogService $logService;

    public function __construct(EmailService $mailer, CommunicationLogService $logService)
    {
        $this->mailer = $mailer;
        $this->logService = $logService;
    }

    public function send(array $payload): array
    {
        $recipients = $this->normalizeEmails($payload['recipients'] ?? []);
        $cc = $this->normalizeEmails($payload['cc'] ?? []);
        $bcc = $this->normalizeEmails($payload['bcc'] ?? []);

        if (empty($recipients)) {
            $this->logService->log([
                'student_id' => (int) $payload['student_id'],
                'family_id' => (int) $payload['family_id'],
                'student_name' => (string) $payload['student_name'],
                'template_key' => (string) $payload['template_key'],
                'subject' => (string) $payload['subject'],
                'body' => (string) $payload['body'],
                'recipients' => [],
                'cc' => array_values($cc),
                'bcc' => array_values($bcc),
                'status' => 'failed',
                'error_message' => 'No recipients provided',
                'sent_by' => (int) ($payload['sent_by'] ?? 0),
                'metadata' => null,
            ]);

            return [
                'ok' => false,
                'error' => 'No recipients provided',
            ];
        }

        $sendOk = false;
        $error = null;

        try {
            $sendOk = $this->mailer->send(
                $recipients,
                (string) $payload['subject'],
                (string) $payload['body'],
                'general',
                $cc,
                $bcc
            );
        } catch (\Throwable $t) {
            $error = $t->getMessage();
            $sendOk = false;
        }

        if (!$sendOk && $error === null) {
            $error = 'Mailer returned false';
        }

        $this->logService->log([
            'student_id' => (int) $payload['student_id'],
            'family_id' => (int) $payload['family_id'],
            'student_name' => (string) $payload['student_name'],
            'template_key' => (string) $payload['template_key'],
            'subject' => (string) $payload['subject'],
            'body' => (string) $payload['body'],
            'recipients' => array_values($recipients),
            'cc' => array_values($cc),
            'bcc' => array_values($bcc),
            'status' => $sendOk ? 'sent' : 'failed',
            'error_message' => $error,
            'sent_by' => (int) ($payload['sent_by'] ?? 0),
            'metadata' => null,
        ]);

        return [
            'ok' => $sendOk,
            'error' => $error,
        ];
    }

    private function normalizeEmails(array $values): array
    {
        $out = array_values(array_unique(array_filter(array_map('strval', $values))));
        return array_values(array_filter($out, static function ($email) {
            return $email !== '';
        }));
    }
}
