<?php

namespace App\Services;

use App\Jobs\SendAdminQnaCreatedMailJob;
use App\Repositories\Cs\CsQnaRepository;
use App\Support\LegacyCrypto\CiSeedCrypto;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

final class QnaService
{
    public function __construct(
        private readonly CsQnaRepository $repo,
        private readonly CiSeedCrypto $seed,
    ) {}

    public function paginateMyQna(int $memNo, int $perPage = 10, int $year = 0): LengthAwarePaginator
    {
        return $this->repo->paginateMyQna($memNo, $perPage, $year);
    }

    public function findMyQna(int $memNo, int $seq, int $year = 0)
    {
        return $this->repo->findMyQna($memNo, $seq, $year);
    }

    public function getEnquiryCodes(): array
    {
        return $this->repo->getEnquiryCodes();
    }

    /**
     * 1:1 문의 등록
     */
    public function createQna(int $memNo, array $payload, ?int $year = null): int
    {
        $year = $year ?: (int) date('Y');

        // 컨트롤러에서 이미 sanitize/검증하지만, 서비스에서도 최소 방어(이중 안전)
        $enquiryCode    = (string)($payload['enquiry_code'] ?? '');
        $enquiryTitle   = strip_tags(trim((string)($payload['enquiry_title'] ?? '')));
        $enquiryContent = strip_tags(trim((string)($payload['enquiry_content'] ?? '')));
        $returnType     = (string)($payload['return_type'] ?? 'web');

        $id = $this->repo->insertQna($memNo, [
            'enquiry_code'    => $enquiryCode,
            'enquiry_title'   => $enquiryTitle,
            'enquiry_content' => $enquiryContent,
            'return_type'     => $returnType,
        ], $year);

        // 메일 발송 데이터 구성
        $userEmail = (string)($payload['_user_email'] ?? '');
        $userName  = (string)($payload['_user_name'] ?? '');
        $ip        = (string)($payload['_ip'] ?? '');
        $cellEnc   = (string)($payload['_user_cell_enc'] ?? '');

        $cellPlain = '';
        try {
            $cellPlain = (string) $this->seed->decrypt($cellEnc);
        } catch (\Throwable $e) {
            $cellPlain = ''; // 복호화 실패해도 문의 등록은 유지
        }

        SendAdminQnaCreatedMailJob::dispatch($memNo, $id, [
            'name'            => $userName,
            'email'           => $userEmail,
            'cell'            => $cellPlain,
            'ip'              => $ip,
            'year'            => $year,
            'enquiry_code'    => $enquiryCode,
            'enquiry_title'   => $enquiryTitle,
            'enquiry_content' => $enquiryContent,
            'return_type'     => $returnType,
            'created_at'      => now()->toDateTimeString(),
        ])->onConnection('redis');

        return $id;
    }
}
