<?php

namespace App\Http\Controllers\Admin\Services;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Services\LetterRequestRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\LetterRequest;
use App\Services\Admin\Services\LetterRequestService;
use App\Services\Admin\Users\StudentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class LetterRequestController extends Controller
{
    public function __construct(
        private readonly LetterRequestService $service,
        private readonly StudentService $studentService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/services/letter-requests/index', [
            'letterRequests' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                status: $request->validated('status'),
            ),
            'students' => $this->studentService->getAllForSelect(),
            'filters' => $request->only(['status']),
        ]);
    }

    public function store(LetterRequestRequest $request): RedirectResponse
    {
        $this->service->create($request->validated(), $request->file('result'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Surat permohonan berhasil ditambahkan.']);

        return to_route('admin.services.letter-requests.index');
    }

    public function update(LetterRequestRequest $request, LetterRequest $letterRequest): RedirectResponse
    {
        $this->service->update($letterRequest, $request->validated(), $request->file('result'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Surat permohonan berhasil diperbarui.']);

        return to_route('admin.services.letter-requests.index');
    }

    public function destroy(LetterRequest $letterRequest): RedirectResponse
    {
        $this->service->delete($letterRequest);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Surat permohonan berhasil dihapus.'])->back();
    }
}
