<?php

namespace App\Http\Controllers\Api\Scores;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Scores\ScoreAddColumnRequest;
use App\Http\Requests\Scores\ScoreUpdateRequest;
use App\Http\Resources\Scores\ScoreStudentResource;
use App\Models\Student;
use App\Services\Scores\HomeworkScoreService;
use App\Services\Scores\SemesterScoreService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class HomeworkController extends BaseApiController
{
    public function __construct(
        private HomeworkScoreService $service,
        private SemesterScoreService $semesterScoreService
    ) {
        parent::__construct();
    }

    public function index(Request $request): JsonResponse
    {
        $data = array_merge($request->query->all(), $request->all(), $request->json()->all());
        $validator = Validator::make($data, [
            'class_section_id' => ['required', 'integer', 'min:1'],
            'semester' => ['nullable', 'string', 'max:50'],
            'school_year' => ['nullable', 'string', 'max:50'],
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $payload = $validator->validated();
        $data = $this->service->list(
            (int) $payload['class_section_id'],
            $payload['semester'] ?? null,
            $payload['school_year'] ?? null
        );

        return response()->json([
            'ok' => true,
            'students' => ScoreStudentResource::collection($data['students']),
            'headers' => $data['headers'],
            'semester' => $data['semester'],
            'school_year' => $data['schoolYear'],
            'scores_locked' => $data['scoresLocked'],
            'missing_ok_map' => $data['missingOkMap'],
        ]);
    }

    public function update(ScoreUpdateRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $count = $this->service->update(
            (int) $payload['class_section_id'],
            (string) $payload['semester'],
            (string) $payload['school_year'],
            $payload['scores'],
            $payload['missing_ok'] ?? [],
            (int) (auth()->id() ?? 0)
        );

        $this->refreshSemesterScores((int) $payload['class_section_id'], (string) $payload['semester'], (string) $payload['school_year']);

        return response()->json(['ok' => true, 'updated' => $count]);
    }

    public function addColumn(ScoreAddColumnRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $nextIndex = $this->service->addColumn(
            (int) $payload['class_section_id'],
            (string) $payload['semester'],
            (string) $payload['school_year'],
            (int) (auth()->id() ?? 0)
        );

        return response()->json(['ok' => true, 'homework_index' => $nextIndex]);
    }

    private function refreshSemesterScores(int $classSectionId, string $semester, string $schoolYear): void
    {
        $studentInfo = Student::getStudentInfoByClassSectionId($classSectionId, $semester, $schoolYear, (int) (auth()->id() ?? 0));
        if (empty($studentInfo)) {
            return;
        }
        try {
            $this->semesterScoreService->updateScoresForStudents($studentInfo, $semester, $schoolYear);
        } catch (\Throwable $e) {
        }
    }
}
