<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\AnnouncementRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Announcement;
use App\Services\Admin\Manage\AnnouncementService;
use App\Services\Admin\Master\DepartmentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AnnouncementController extends Controller
{
    public function __construct(
        private readonly AnnouncementService $service,
        private readonly DepartmentService $departmentService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/manage/announcements/index', [
            'announcements' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                departmentId: $request->validated('department_id'),
            ),
            'departments' => $this->departmentService->getAllForSelect(),
            'filters' => $request->only(['department_id']),
        ]);
    }

    public function store(AnnouncementRequest $request): RedirectResponse
    {
        $this->service->create($request->validated());

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

        return to_route('admin.manage.announcements.index');
    }

    public function update(AnnouncementRequest $request, Announcement $announcement): RedirectResponse
    {
        $this->service->update($announcement, $request->validated());

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

        return to_route('admin.manage.announcements.index');
    }

    public function destroy(Announcement $announcement): RedirectResponse
    {
        $this->service->delete($announcement);

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