<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Attendance\TeacherSubmitAttendanceRequest;
use App\Http\Resources\Attendance\TeacherAttendanceFormResource;
use App\Http\Resources\Attendance\TeacherGridResource;
use App\Services\Attendance\AttendanceQueryService;
use App\Services\Attendance\AttendanceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class TeacherAttendanceApiController extends Controller
{
    public function __construct(
        protected AttendanceQueryService $queryService,
        protected AttendanceService $attendanceService
    ) {}

    public function grid(Request $request): TeacherGridResource
    {
        $semester = (string)($request->query('semester') ?: $this->attendanceService->currentSemester());
        $schoolYear = (string)($request->query('school_year') ?: $this->attendanceService->currentSchoolYear());
        $date = (string)($request->query('date') ?: now()->toDateString());
        $sectionCode = (int)$request->query('class_section_id', 0);

        return new TeacherGridResource(
            $this->queryService->teacherGrid($semester, $schoolYear, $date, $sectionCode)
        );
    }

    public function form(Request $request): JsonResponse|TeacherAttendanceFormResource
    {
        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        try {
            return new TeacherAttendanceFormResource(
                $this->queryService->teacherAttendanceFormData(
                    $guard,
                    (int)$request->query('class_section_id', 0)
                )
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function submit(TeacherSubmitAttendanceRequest $request): JsonResponse
    {
        $user = auth()->user();
        if ($user === null) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        try {
            return response()->json(
                $this->attendanceService->submitTeacherAttendance($user, $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        return $userId;
    }
}