<?php

namespace App\Http\Controllers\Api\Subjects;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Subjects\SubjectCurriculumStoreRequest;
use App\Http\Requests\Subjects\SubjectCurriculumUpdateRequest;
use App\Http\Resources\Subjects\SubjectClassResource;
use App\Http\Resources\Subjects\SubjectCurriculumResource;
use App\Models\SubjectCurriculum;
use App\Services\Subjects\SubjectCurriculumService;
use Illuminate\Http\JsonResponse;

class SubjectCurriculumController extends BaseApiController
{
    public function __construct(private SubjectCurriculumService $service)
    {
        parent::__construct();
    }

    public function index(): JsonResponse
    {
        $data = $this->service->list();

        return response()->json([
            'ok' => true,
            'classes' => SubjectClassResource::collection($data['classes']),
            'entries' => SubjectCurriculumResource::collection($data['entries']),
            'subject_labels' => $data['subject_labels'],
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $entry = SubjectCurriculum::query()->find($id);
        if (!$entry) {
            return response()->json(['ok' => false, 'message' => 'Curriculum entry not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'entry' => new SubjectCurriculumResource($entry->toArray()),
        ]);
    }

    public function store(SubjectCurriculumStoreRequest $request): JsonResponse
    {
        $entry = $this->service->store($request->validated());

        return response()->json([
            'ok' => true,
            'entry' => new SubjectCurriculumResource($entry->toArray()),
        ], 201);
    }

    public function update(SubjectCurriculumUpdateRequest $request, int $id): JsonResponse
    {
        $entry = $this->service->update($id, $request->validated());
        if (!$entry) {
            return response()->json(['ok' => false, 'message' => 'Curriculum entry not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'entry' => new SubjectCurriculumResource($entry->toArray()),
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $deleted = $this->service->delete($id);
        if (!$deleted) {
            return response()->json(['ok' => false, 'message' => 'Curriculum entry not found.'], 404);
        }

        return response()->json(['ok' => true]);
    }
}
