<?php

namespace App\Repositories\Cs;

use App\Models\CounselingOneOnOne;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

final class CsQnaRepository
{
    private function resolveYear(int $year = 0): int
    {
        return $year > 0 ? $year : (int) date('Y');
    }

    private function table(int $year): string
    {
        return "counseling_one_on_one_{$year}";
    }

    private function emptyPaginator(int $perPage): LengthAwarePaginator
    {
        return new Paginator([], 0, $perPage, 1, [
            'path'  => request()->url(),
            'query' => request()->query(),
        ]);
    }

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

        if (!Schema::hasTable($table)) {
            return $this->emptyPaginator($perPage);
        }

        return CounselingOneOnOne::queryForYear($year)
            ->from("{$table} as q")
            ->leftJoin('counseling_code as cc', function ($join) {
                $join->on('cc.enquiry_code', '=', 'q.enquiry_code')
                    ->where('cc.enquiry_type', '=', 'e');
            })
            ->where('q.member_num', $memNo)
            ->select([
                'q.seq',
                'q.state',
                'q.enquiry_code',
                'q.enquiry_title',
                'q.regdate',
                'cc.enquiry_title as enquiry_code_name',
            ])
            ->orderByDesc('q.seq')
            ->paginate($perPage)
            ->withQueryString();
    }

    public function findMyQna(int $memNo, int $seq, int $year = 0)
    {
        $year  = $this->resolveYear($year);
        $table = $this->table($year);

        if (!Schema::hasTable($table)) {
            abort(404);
        }

        return CounselingOneOnOne::queryForYear($year)
            ->from("{$table} as q")
            ->leftJoin('counseling_code as cc', function ($join) {
                $join->on('cc.enquiry_code', '=', 'q.enquiry_code')
                    ->where('cc.enquiry_type', '=', 'e');
            })
            ->where('q.member_num', $memNo)
            ->where('q.seq', $seq)
            ->select([
                'q.seq',
                'q.state',
                'q.enquiry_code',
                'q.enquiry_title',
                'q.enquiry_content',
                'q.answer_content',
                'q.regdate',
                'cc.enquiry_title as enquiry_code_name',
            ])
            ->firstOrFail();
    }

    public function getEnquiryCodes(): array
    {
        return DB::table('counseling_code')
            ->where('enquiry_type', 'e')
            ->orderBy('enquiry_code', 'asc')
            ->get(['enquiry_code', 'enquiry_title'])
            ->map(fn($r) => ['code' => (string)$r->enquiry_code, 'title' => (string)$r->enquiry_title])
            ->all();
    }

    /**
     * QnA insert (연도 테이블)
     */
    public function insertQna(int $memNo, array $data, int $year = 0): int
    {
        $year  = $this->resolveYear($year);
        $table = $this->table($year);

        if (!Schema::hasTable($table)) {
            throw new \RuntimeException("qna_table_not_found: {$table}");
        }

        return (int) DB::transaction(function () use ($table, $memNo, $data) {
            return DB::table($table)->insertGetId([
                'state'           => 'a',
                'member_num'      => $memNo,
                'enquiry_code'    => (string)($data['enquiry_code'] ?? ''),
                'enquiry_title'   => (string)($data['enquiry_title'] ?? ''),
                'enquiry_content' => (string)($data['enquiry_content'] ?? ''),
                'return_type'     => (string)($data['return_type'] ?? 'web'),
                'user_upload'     => null,
                'regdate'         => now()->format('Y-m-d H:i:s'),
                'receipt_date'    => "1900-01-01 00:00:00",
                'defer_date'      => "1900-01-01 00:00:00",
                'completion_date' => "1900-01-01 00:00:00",
            ]);
        });
    }
}
