<?php

namespace App\Http\Controllers\Web\Mypage;

use App\Http\Controllers\Controller;
use App\Services\QnaService;
use Illuminate\Http\Request;

final class MypageQnaController extends Controller
{
    public function __construct(
        private readonly QnaService $qnaService
    ) {}

    public function index(Request $request)
    {
        $memNo = (int) data_get($request->session()->all(), '_sess._mno', 0);
        if ($memNo <= 0) {
            return redirect()->route('web.mypage.info.index');
        }

        $year = $this->normalizeYear((int)$request->query('year', (int)date('Y')));

        $items = $this->qnaService->paginateMyQna($memNo, 10, $year);

        return view('web.mypage.qna.index', [
            'items'  => $items,
            'detail' => null,
            'seq'    => null,
            'year'   => $year,
            'years'  => range(2018, (int)date('Y')),
        ]);
    }

    public function show(Request $request, int $seq)
    {
        $memNo = (int) data_get($request->session()->all(), '_sess._mno', 0);
        if ($memNo <= 0) {
            return redirect()->route('web.mypage.info.index');
        }

        $year = $this->normalizeYear((int)$request->query('year', (int)date('Y')));

        $items  = $this->qnaService->paginateMyQna($memNo, 10, $year);
        $detail = $this->qnaService->findMyQna($memNo, $seq, $year);

        return view('web.mypage.qna.index', [
            'items'  => $items,
            'detail' => $detail,
            'seq'    => $seq,
            'year'   => $year,
            'years'  => range(2018, (int)date('Y')),
        ]);
    }

    private function normalizeYear(int $year): int
    {
        $min = 2018;
        $max = (int)date('Y');
        if ($year < $min) return $min;
        if ($year > $max) return $max;
        return $year;
    }
}
