<?php

namespace App\Services;

use App\Repositories\Member\EmailAuthRepository;
use App\Services\MailService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class EmailVerificationService
{
    public function __construct(
        private readonly EmailAuthRepository $emailAuthRepo,
        private readonly MailService $mail,
    ) {}

    public function getAuthUserFromSession(Request $request): array
    {
        $au = (array) $request->session()->get('auth_user', []);

        $memNo = (int)($au['mem_no'] ?? 0);
        $email = (string)($au['email'] ?? '');
        $expiresAt = (int)($au['expires_at'] ?? 0);

        if ($memNo <= 0 || $email === '' || $expiresAt <= 0 || now()->timestamp > $expiresAt) {
            $request->session()->forget('auth_user');
            return [];
        }

        return ['mem_no' => $memNo, 'email' => $email, 'expires_at' => $expiresAt];
    }

    public function sendVerifyMail(Request $request, int $memNo, string $email): array
    {
        $prep = $this->emailAuthRepo->prepareEmailVerify(
            $memNo,
            $email,
            (string)$request->ip(),
            30
        );

        $link = URL::temporarySignedRoute(
            'web.auth.email.verify',
            now()->addMinutes(30),
            [
                'mem_no' => $memNo,
                'k'      => $prep['auth_key'],
            ]
        );

        $this->mail->sendTemplate(
            $email,
            '[PIN FOR YOU] 이메일 인증을 완료해 주세요',
            'mail.auth.verify_email',
            [
                'email' => $email,
                'link' => $link,
                'expires_min' => 30,
                'accent' => '#E4574B',
                'brand' => 'PIN FOR YOU',
                'siteUrl' => config('app.url'),
            ],
            queue: false
        );

        return ['ok' => true, 'status' => 200, 'message' => '인증메일을 발송했습니다. 메일함을 확인해 주세요.'];
    }

    public function verifySignedLink(Request $request, int $memNo, string $k): array
    {
        return $this->emailAuthRepo->confirmEmailVerify(
            $memNo,
            $k,
            (string)$request->ip(),
            (string)$request->userAgent()
        );
    }
}
