<?php

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Semesters\SchoolYearRangeRequest;
use App\Http\Requests\Semesters\SemesterNormalizeRequest;
use App\Http\Requests\Semesters\SemesterRangeRequest;
use App\Http\Requests\Semesters\SemesterResolveRequest;
use App\Http\Resources\Semesters\SemesterRangeResource;
use App\Http\Resources\Semesters\SemesterResolveResource;
use App\Services\SemesterRangeService;
use Illuminate\Http\JsonResponse;

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

    public function schoolYearRange(SchoolYearRangeRequest $request): JsonResponse
    {
        $payload = $request->validated();
        [$start, $end] = $this->service->getSchoolYearRange($payload['school_year']);

        return response()->json([
            'ok' => true,
            'school_year' => $payload['school_year'],
            'range' => new SemesterRangeResource([
                'start_date' => $start,
                'end_date' => $end,
            ]),
        ]);
    }

    public function semesterRange(SemesterRangeRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $range = $this->service->getSemesterRange($payload['school_year'], $payload['semester']);

        if ($range === null) {
            return response()->json(['ok' => false, 'message' => 'Invalid semester range.'], 422);
        }

        return response()->json([
            'ok' => true,
            'school_year' => $payload['school_year'],
            'semester' => $this->service->normalizeSemester($payload['semester']),
            'range' => new SemesterRangeResource([
                'start_date' => $range[0],
                'end_date' => $range[1],
            ]),
        ]);
    }

    public function normalize(SemesterNormalizeRequest $request): JsonResponse
    {
        $payload = $request->validated();

        return response()->json([
            'ok' => true,
            'normalized' => $this->service->normalizeSemester($payload['semester']),
        ]);
    }

    public function resolve(SemesterResolveRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $semester = $this->service->getSemesterForDate($payload['date'] ?? null);

        return response()->json([
            'ok' => true,
            'resolution' => new SemesterResolveResource([
                'date' => $payload['date'] ?? null,
                'semester' => $semester,
            ]),
        ]);
    }
}
