<?php

/**
 * 文件功能：系统邮件 SMTP 专属配置控制器
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SysParam;
use App\Services\ChatStateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;

class SmtpController extends Controller
{
    public function __construct(
        private readonly ChatStateService $chatState
    ) {}

    /**
     * 显示 SMTP 专属配置表单
     */
    public function edit(): View
    {
        // 仅抓取以 smtp_ 开头的配置项
        $params = SysParam::where('alias', 'like', 'smtp_%')->pluck('body', 'alias')->toArray();
        $descriptions = SysParam::where('alias', 'like', 'smtp_%')->pluck('guidetxt', 'alias')->toArray();

        return view('admin.smtp.edit', compact('params', 'descriptions'));
    }

    /**
     * 更新 SMTP 配置，并刷新全站 Cache 缓存
     */
    public function update(Request $request): RedirectResponse
    {
        $data = $request->except(['_token', '_method']);

        foreach ($data as $alias => $body) {
            SysParam::updateOrCreate(
                ['alias' => $alias],
                ['body' => $body ?? '']
            );

            // 写入 Cache 保证极速读取
            $this->chatState->setSysParam($alias, $body ?? '');

            // 清除 Sysparam 模型的内部缓存
            SysParam::clearCache($alias);
        }

        return redirect()->route('admin.smtp.edit')->with('success', 'SMTP 发信配置已成功保存更新！');
    }

    /**
     * 发送测试邮件
     */
    public function test(Request $request): RedirectResponse
    {
        $request->validate([
            'test_email' => 'required|email',
        ]);

        $testEmail = $request->input('test_email');

        try {
            Mail::raw('您好，这是一封来自【飘落流星聊天室】系统的测试邮件，当您看到这封邮件，说明系统后台您的 SMTP 设置已经完全畅通无误。', function ($message) use ($testEmail) {
                $message->to($testEmail)
                    ->subject('飘落流星聊天室 - SMTP 发信测试');
            });

            return redirect()->route('admin.smtp.edit')->with('success', "测试邮件已成功发送至 {$testEmail}，请注意查收。");
        } catch (\Throwable $e) {
            return redirect()->route('admin.smtp.edit')->with('error', '测试发出失败，原因：'.$e->getMessage());
        }
    }
}
