<?php

namespace App\Modules\Mini\Services;

use App\Base\BaseService;
use App\Exceptions\ClientException;
use App\Mail\ForgetPasswordEmail;
use App\Mail\RegisterEmail;
use Illuminate\Support\Facades\Mail;

class EmailService extends BaseService
{
    public function emailCaptcha($email, $source)
    {
        switch ($source) {
            case "register":
                return $this->register($email);
            case "forgetPassword":
                return $this->forgetPassword($email);
            default:
                throw new ClientException("source未匹配");
        }
    }

    private function register($email): bool
    {
        $captcha = app(CaptchaService::class)->createCaptcha($email);

        try {
            Mail::to($email)->send(new RegisterEmail($captcha));
        } catch (\Exception $e) {
            logger()->error("邮件发送失败  " . $e->getMessage());
            throw new ClientException("邮件发送失败,请稍后再试");
        }

        return true;
    }

    private function forgetPassword($email): bool
    {
        $captcha = app(CaptchaService::class)->createCaptcha($email);

        try {
            Mail::to($email)->send(new ForgetPasswordEmail($captcha));
        } catch (\Exception $e) {
            logger()->error("邮件发送失败  " . $e->getMessage());
            throw new ClientException("邮件发送失败,请稍后再试");
        }

        return true;
    }
}