<?php

namespace Kylin\Notification\Channels;

use Illuminate\Support\Facades\Mail;
use Kylin\Notification\Contracts\ChannelInterface;
use Kylin\Notification\Models\Notification;

class MailChannel implements ChannelInterface
{
    public function send(Notification $notification, array $params = []): array
    {
        try {
            $to = $params['to'] ?? $params['email'] ?? null;
            $subject = $params['subject'] ?? $notification->title;
            $body = $params['body'] ?? $notification->content;
            $mailableClass = $params['mailable'] ?? null;

            if (!$to) {
                return ['success' => false, 'message_id' => null, 'error' => 'Missing email address', 'raw_response' => null];
            }

            if ($mailableClass && class_exists($mailableClass)) {
                $mailable = new $mailableClass($notification, $params);
                Mail::to($to)->send($mailable);
            } else {
                // 简单文本邮件
                Mail::raw($body, function ($message) use ($to, $subject) {
                    $message->to($to)->subject($subject);
                });
            }

            return [
                'success' => true,
                'message_id' => null,
                'error' => null,
                'raw_response' => null,
            ];
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message_id' => null,
                'error' => $e->getMessage(),
                'raw_response' => null,
            ];
        }
    }

    public function getName(): string
    {
        return 'mail';
    }
}
