<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\AssignmentRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Assignment;
use App\Services\Admin\AcademicClasses\AssignmentService;
use App\Services\Admin\Manage\CourseClassService;
use App\Services\Admin\Master\AcademicTermService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AssignmentController extends Controller
{
    public function __construct(
        private readonly AssignmentService $service,
        private readonly CourseClassService $courseClassService,
        private readonly AcademicTermService $academicTermService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        $academicTermId = $request->has('academic_term_id')
            ? $request->validated('academic_term_id')
            : $this->academicTermService->getActive()?->id;

        return Inertia::render('admin/academic-classes/assignments/index', [
            'assignments' => Inertia::scroll(fn () => $this->service->paginated(
                $request->user(),
                ...$request->validatedWithDefaults(),
                courseClassId: $request->validated('course_class_id'),
                academicTermId: $academicTermId,
            )),
            'courseClasses' => $this->courseClassService->getAllForSelect($request->user()),
            'academicTerms' => $this->academicTermService->getAllForSelect(),
            'filters' => [
                'course_class_id' => $request->validated('course_class_id'),
                'academic_term_id' => $academicTermId ? (string) $academicTermId : null,
            ],
        ]);
    }

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

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

        return to_route('admin.academic-classes.assignments.index');
    }

    public function update(AssignmentRequest $request, Assignment $assignment): RedirectResponse
    {
        $this->service->update($assignment, $request->validated(), $request->file('attachment'));

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

        return to_route('admin.academic-classes.assignments.index');
    }

    public function destroy(Assignment $assignment): RedirectResponse
    {
        $this->service->delete($assignment);

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