<?php

namespace App\Http\Controllers\Admin\Services;

use App\Enums\LetterStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Services\LetterRequest\LetterRequestRequest;
use App\Http\Requests\Admin\Services\LetterRequest\LetterRequestStatusRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\LetterRequest;
use App\Services\Admin\Services\LetterRequestService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

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

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

    public function store(LetterRequestRequest $request): RedirectResponse
    {
        $this->service->create([
            'user_id' => auth()->id(),
            ...$request->validated(),
        ]);

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

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

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

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

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

    public function destroy(LetterRequest $letterRequest): RedirectResponse
    {
        abort_if($letterRequest->status !== LetterStatus::Submitted->value, 403);

        $this->service->delete($letterRequest);

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

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

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