<?php

namespace App\Http\Controllers\Api\Attendance;

use App\Http\Controllers\Controller;
use App\Http\Requests\Attendance\AdminAddAttendanceEntryRequest;
use App\Http\Requests\Attendance\UpdateAttendanceManagementRequest;
use App\Http\Resources\Attendance\DailyAttendanceResource;
use App\Services\Attendance\AttendanceQueryService;
use App\Services\Attendance\AttendanceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

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

    public function dailyData(Request $request): DailyAttendanceResource
    {
        return new DailyAttendanceResource(
            $this->queryService->buildDailyAttendanceData(
                (string)$request->query('semester', $this->attendanceService->currentSemester()),
                (string)$request->query('school_year', $this->attendanceService->currentSchoolYear())
            )
        );
    }

    public function updateManagement(UpdateAttendanceManagementRequest $request): JsonResponse
    {
        try {
            return response()->json(
                $this->attendanceService->updateAttendanceManagement(auth()->user(), $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    public function addEntry(AdminAddAttendanceEntryRequest $request): JsonResponse
    {
        try {
            return response()->json(
                $this->attendanceService->adminAddEntry(auth()->user(), $request->validated())
            );
        } catch (Throwable $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }
}