<?php

namespace App\Http\Controllers\Web\Cs;

use App\Http\Controllers\Controller;
use App\Services\CsNoticeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

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

    public function index(Request $request)
    {
        $data = $request->validate([
            'q' => ['nullable', 'string', 'max:200'],
        ]);

        $q = trim((string)($data['q'] ?? ''));

        $notices = $this->service->paginate($q, 15);

        return view('web.cs.notice.index', [
            'notices' => $notices,
            'q'       => $q,
        ]);
    }

    public function show(Request $request, int $seq)
    {
        $res = $this->service->detail($seq, $request->session());

        return view('web.cs.notice.show', $res);
    }

    public function download(int $seq, int $slot): StreamedResponse
    {
        $r = $this->service->download($seq, $slot);
        abort_unless($r['ok'], 404);

        return Storage::disk('public')->download($r['path'], $r['name']);
    }
}
