<?php
namespace App\Http\Controllers\Admin\Mail;

use App\Http\Controllers\Controller;
use App\Services\Admin\Mail\AdminMailService;
use Illuminate\Http\Request;

final class AdminMailLogController extends Controller
{
    public function __construct(private readonly AdminMailService $service) {}

    public function index(Request $request)
    {
        $filters = $request->validate([
            'status'    => ['nullable','in:scheduled,queued,sending,sent,partial,failed,canceled'],
            'send_mode' => ['nullable','in:one,many,csv,template,db'],
            'date_from' => ['nullable','date'],
            'date_to'   => ['nullable','date'],
            'q'         => ['nullable','string','max:120'],
        ]);

        $page = $this->service->listBatches($filters, perPage: 20);

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

    public function show(Request $request, int $batchId)
    {
        $filters = $request->validate([
            'status' => ['nullable','in:queued,sent,failed,canceled,skipped'],
            'to'     => ['nullable','string','max:190'],
            'q'      => ['nullable','string','max:120'],
        ]);

        $res = $this->service->getBatchDetail($batchId, $filters, perPage: 50);
        if (!$res['ok']) abort(404);

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

    public function cancel(int $batchId)
    {
        $adminId = (int)auth('admin')->id();
        $res = $this->service->cancelBatch($adminId, $batchId);

        return back()->with('toast', [
            'type' => $res['ok'] ? 'success' : 'danger',
            'title'=> $res['ok'] ? '처리 완료' : '실패',
            'message' => $res['message'] ?? ($res['ok'] ? '취소 처리했습니다.' : '취소 실패'),
        ]);
    }

    public function retryFailed(int $batchId)
    {
        $adminId = (int)auth('admin')->id();
        $res = $this->service->retryFailed($adminId, $batchId);

        return back()->with('toast', [
            'type' => $res['ok'] ? 'success' : 'danger',
            'title'=> $res['ok'] ? '재시도 시작' : '실패',
            'message' => $res['message'] ?? '',
        ]);
    }
}
