<?php

namespace App\Http\Controllers\Api\Scores;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Scores\ScoreLockRequest;
use App\Http\Requests\Scores\ScoreOverviewRequest;
use App\Http\Requests\Scores\ScoreStudentRequest;
use App\Http\Resources\Scores\ScoreStudentResource;
use App\Services\Scores\ScoreDashboardService;
use Illuminate\Http\JsonResponse;

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

    public function overview(ScoreOverviewRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $teacherId = (int) ($request->user()?->id ?? (auth()->id() ?? 0));
        $classSectionId = $payload['class_section_id'] ?? $request->input('class_section_id');
        $semester = $payload['semester'] ?? $request->input('semester');
        $schoolYear = $payload['school_year'] ?? $request->input('school_year');

        $data = $this->service->overview(
            $teacherId,
            isset($classSectionId) ? (int) $classSectionId : null,
            $semester !== null ? (string) $semester : null,
            $schoolYear !== null ? (string) $schoolYear : null
        );

        return response()->json([
            'ok' => true,
            'students' => ScoreStudentResource::collection($data['students'] ?? []),
            'class_section_id' => $data['class_section_id'] ?? null,
            'class_section_name' => $data['class_section_name'] ?? null,
            'semester' => $data['semester'] ?? null,
            'school_year' => $data['school_year'] ?? null,
            'scores_locked' => $data['scoresLocked'] ?? false,
        ]);
    }

    public function lock(ScoreLockRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $this->service->submitScoresLock(
            (int) $payload['class_section_id'],
            (string) $payload['semester'],
            (string) $payload['school_year'],
            $payload['missing_ok'] ?? [],
            (int) ($request->user()?->id ?? (auth()->id() ?? 0))
        );

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

    public function studentScores(ScoreStudentRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $parentId = (int) ($request->user()?->id ?? (auth()->id() ?? 0));

        $data = $this->service->viewStudentScores($parentId, (string) $payload['school_year']);

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