<?php

namespace App\Http\Controllers\Admin\Sms;

use App\Http\Controllers\Controller;
use App\Services\Admin\Sms\AdminSmsLogService;
use Illuminate\Http\Request;

final class AdminSmsLogController extends Controller
{
    public function __construct(
        private readonly AdminSmsLogService $service,
    ) {}

    public function index(Request $request)
    {
        $statusKeys = array_keys($this->service->getStatusLabels());
        $modeKeys   = array_keys($this->service->getModeLabels());

        $filters = $request->validate([
            'status'    => ['nullable', 'in:'.implode(',', $statusKeys)],
            'send_mode' => ['nullable', 'in:'.implode(',', $modeKeys)],
            'date_from' => ['nullable', 'date'],
            'date_to'   => ['nullable', 'date'],
            'q'         => ['nullable', 'string', 'max:120'],
        ]);

        $batches = $this->service->paginateBatches($filters, 20);

        return view('admin.sms.logs.index', [
            'batches'    => $batches,
            'filters'    => $filters,
            'labels'     => $this->service->getStatusLabels(),
            'modeLabels' => $this->service->getModeLabels(),
        ]);
    }

    public function show(int $batchId, Request $request)
    {
        $batch = $this->service->getBatch($batchId);
        if (!$batch) {
            return redirect()->route('admin.sms.logs')->with('toast', [
                'type' => 'danger',
                'title' => '없음',
                'message' => '해당 발송 이력을 찾을 수 없습니다.',
            ]);
        }

        $itemStatusKeys = array_keys($this->service->getItemStatusLabels());

        $filters = $request->validate([
            'status' => ['nullable', 'in:'.implode(',', $itemStatusKeys)],
            'to'     => ['nullable', 'string', 'max:40'],
            'q'      => ['nullable', 'string', 'max:120'],
        ]);

        $items = $this->service->paginateItems($batchId, $filters, 50);

        return view('admin.sms.logs.show', [
            'batch'      => $batch,
            'items'      => $items,
            'filters'    => $filters,
            'labels'     => $this->service->getStatusLabels(),
            'modeLabels' => $this->service->getModeLabels(),
            'itemLabels' => $this->service->getItemStatusLabels(),
        ]);
    }
}
