<?php

namespace App\Services\Notification\Adapters;

use App\Models\NotificationDelivery;
use App\Services\Notification\Contracts\NotificationChannelAdapter;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class EmailAdapter implements NotificationChannelAdapter
{
    public function send(NotificationDelivery $delivery): array
    {
        $config = $delivery->channelConfig;
        $credentials = $config?->credentials ?? [];
        $settings = $config?->settings ?? [];
        if (! $delivery->destination || empty($settings['host'])) {
            throw ValidationException::withMessages(['channel' => 'Alamat penerima atau konfigurasi SMTP belum lengkap.']);
        }
        $original = Config::get('mail.mailers.smtp');
        $originalFrom = Config::get('mail.from');
        try {
            Config::set('mail.mailers.smtp', [
                'transport' => 'smtp',
                'host' => $settings['host'],
                'port' => $settings['port'] ?? 587,
                'encryption' => $settings['encryption'] ?? 'tls',
                'username' => $credentials['username'] ?? null,
                'password' => $credentials['password'] ?? null,
                'timeout' => 30,
            ]);
            Config::set('mail.from', [
                'address' => $settings['from_address'],
                'name' => $settings['from_name'] ?? null,
            ]);
            Mail::purge('smtp');
            Mail::raw($delivery->rendered_body, function ($mail) use ($delivery) {
                $mail->to($delivery->destination)->subject($delivery->rendered_subject ?: 'Notifikasi');
            });
        } finally {
            Config::set('mail.mailers.smtp', $original);
            Config::set('mail.from', $originalFrom);
            Mail::purge('smtp');
        }

        return ['provider_message_id' => (string) Str::uuid(), 'response' => ['accepted' => true]];
    }
}
