<?php

namespace App\Services;

use App\Models\Verification;
use App\Notifications\SendVerificationEmailCode;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class VerificationEmailSender
{
    public function send(Verification $verification): bool
    {
        if (empty($verification->email)) {
            return false;
        }

        if ($this->sendViaZeptoMailApi($verification)) {
            return true;
        }

        try {
            $verification->notify(new SendVerificationEmailCode($verification));

            return true;
        } catch (\Throwable $e) {
            Log::warning('verification.email.smtp_failed', [
                'verification_id' => $verification->id,
                'email' => $verification->email,
                'message' => $e->getMessage(),
            ]);
        }

        return false;
    }

    private function sendViaZeptoMailApi(Verification $verification): bool
    {
        $apiKey = $this->resolveZeptoMailApiKey();
        if ($apiKey === '') {
            return false;
        }

        $from = config('services.zeptomail.from_address')
            ?: config('mail.from.address')
            ?: env('MAIL_FROM_ADDRESS');

        if (empty($from)) {
            return false;
        }

        $generalSettings = getGeneralSettings();
        $subject = trans('auth.email_confirmation');
        $siteName = $generalSettings['site_name'] ?? config('app.name');

        $confirm = [
            'title' => $subject . ' ' . trans('auth.in') . ' ' . $siteName,
            'message' => trans('auth.email_confirmation_template_body', [
                'email' => $verification->email,
                'site' => $siteName,
            ]),
            'code' => $verification->code,
        ];

        $html = View::make('web.default.emails.confirmCode', [
            'confirm' => $confirm,
            'generalSettings' => $generalSettings,
        ])->render();

        $fromName = config('services.zeptomail.from_name')
            ?: config('mail.from.name')
            ?: $siteName;

        try {
            $response = Http::timeout(30)
                ->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Zoho-enczapikey ' . $apiKey,
                ])
                ->post(config('services.zeptomail.api_url', 'https://api.zeptomail.com/v1.1/email'), [
                    'from' => [
                        'address' => $from,
                        'name' => $fromName,
                    ],
                    'to' => [
                        [
                            'email_address' => [
                                'address' => $verification->email,
                            ],
                        ],
                    ],
                    'subject' => $subject,
                    'htmlbody' => $html,
                ]);

            if ($response->successful()) {
                Log::info('verification.email.zeptomail_api_sent', [
                    'verification_id' => $verification->id,
                    'email' => $verification->email,
                ]);

                return true;
            }

            Log::warning('verification.email.zeptomail_api_failed', [
                'verification_id' => $verification->id,
                'status' => $response->status(),
                'body' => $response->body(),
            ]);
        } catch (\Throwable $e) {
            Log::warning('verification.email.zeptomail_api_exception', [
                'verification_id' => $verification->id,
                'message' => $e->getMessage(),
            ]);
        }

        return false;
    }

    private function resolveZeptoMailApiKey(): string
    {
        $key = trim((string) config('services.zeptomail.api_key', ''));

        if ($key !== '') {
            return $key;
        }

        $key = trim((string) env('ZEPTOMAIL_API_KEY', ''));

        if ($key !== '') {
            return $key;
        }

        // ZeptoMail SMTP uses the same send-mail token as the API key.
        $mailPassword = trim((string) env('MAIL_PASSWORD', ''));

        return str_replace('"', '', $mailPassword);
    }
}
