<?php

namespace App\Http\Controllers\Api\Students;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Students\StudentAssignClassRequest;
use App\Http\Requests\Students\StudentAssignmentListRequest;
use App\Http\Requests\Students\StudentAutoDistributeRequest;
use App\Http\Requests\Students\StudentPromotionTotalsRequest;
use App\Http\Requests\Students\StudentRemoveClassRequest;
use App\Http\Requests\Students\StudentSetActiveRequest;
use App\Http\Requests\Students\StudentUpdateRequest;
use App\Http\Resources\Students\StudentAssignmentResource;
use App\Http\Resources\Students\StudentClassSectionResource;
use App\Http\Resources\Students\StudentRemovedResource;
use App\Http\Resources\Students\StudentScoreCardRowResource;
use App\Services\Students\StudentAssignmentService;
use App\Services\Students\StudentAutoDistributionService;
use App\Services\Students\StudentDirectoryService;
use App\Services\Students\StudentProfileService;
use App\Services\Students\StudentScoreCardService;
use App\Services\Students\StudentStatusService;
use Illuminate\Http\JsonResponse;

class StudentController extends BaseApiController
{
    public function __construct(
        private StudentAssignmentService $assignmentService,
        private StudentDirectoryService $directoryService,
        private StudentStatusService $statusService,
        private StudentAutoDistributionService $autoDistributionService,
        private StudentProfileService $profileService,
        private StudentScoreCardService $scoreCardService
    ) {
        parent::__construct();
    }

    public function assignments(StudentAssignmentListRequest $request): JsonResponse
    {
        $data = $this->directoryService->assignmentData($request->validated()['school_year'] ?? null);

        return response()->json([
            'ok' => true,
            'students' => StudentAssignmentResource::collection($data['students']),
            'classes' => StudentClassSectionResource::collection($data['classes']),
            'schoolYears' => $data['schoolYears'],
            'selectedYear' => $data['selectedYear'],
            'currentYear' => $data['currentYear'],
            'isCurrentYear' => $data['isCurrentYear'],
        ]);
    }

    public function assignClass(StudentAssignClassRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->assignmentService->assignClasses(
            (int) $payload['student_id'],
            $payload['class_section_id'],
            (bool) ($payload['is_event_only'] ?? false),
            (int) (auth()->id() ?? 0)
        );

        $status = $result['ok'] ? 200 : 422;

        return response()->json($result + ['ok' => (bool) $result['ok']], $status);
    }

    public function removeClass(StudentRemoveClassRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->assignmentService->removeClass(
            (int) $payload['student_id'],
            (int) $payload['class_section_id'],
            (int) (auth()->id() ?? 0)
        );

        $status = $result['ok'] ? 200 : 422;

        return response()->json($result + ['ok' => (bool) $result['ok']], $status);
    }

    public function removed(StudentAssignmentListRequest $request): JsonResponse
    {
        $data = $this->directoryService->removedStudents($request->validated()['school_year'] ?? null);

        return response()->json([
            'ok' => true,
            'active_students' => StudentRemovedResource::collection($data['active_students']),
            'removed_students' => StudentRemovedResource::collection($data['removed_students']),
            'school_year' => $data['school_year'],
        ]);
    }

    public function setActive(StudentSetActiveRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->statusService->setActive(
            (int) $payload['student_id'],
            (bool) $payload['is_active'],
            (int) (auth()->id() ?? 0)
        );

        $status = $result['ok'] ? 200 : 422;

        return response()->json($result + ['ok' => (bool) $result['ok']], $status);
    }

    public function autoDistribute(StudentAutoDistributeRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->autoDistributionService->autoDistribute(
            (int) ($payload['class_id'] ?? 0),
            (int) $payload['students_per_section'],
            $payload['school_year'] ?? null,
            (int) ($payload['class_section_id'] ?? 0),
            (int) (auth()->id() ?? 0)
        );

        $status = $result['ok'] ? 200 : 422;

        return response()->json($result + ['ok' => (bool) $result['ok']], $status);
    }

    public function promotionTotals(StudentPromotionTotalsRequest $request): JsonResponse
    {
        $data = $this->autoDistributionService->promotionTotals($request->validated()['school_year'] ?? null);

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

    public function update(StudentUpdateRequest $request, int $studentId): JsonResponse
    {
        $result = $this->profileService->updateStudent($studentId, $request->validated());
        $status = $result['ok'] ? 200 : 422;

        return response()->json($result + ['ok' => (bool) $result['ok']], $status);
    }

    public function scoreCard(int $studentId): JsonResponse
    {
        $result = $this->scoreCardService->scoreCard($studentId);
        if (!$result['ok']) {
            return response()->json(['ok' => false, 'message' => $result['message'] ?? 'Not found.'], 404);
        }

        return response()->json([
            'ok' => true,
            'student' => $result['student'],
            'rows' => StudentScoreCardRowResource::collection($result['rows']),
        ]);
    }
}
