<?php

namespace App\Http\Controllers\Api\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Services\PeruDevService;
use App\Traits\AppHelpers;
use Illuminate\Http\JsonResponse;

use App\Enums\DocumentType;
use App\Http\Requests\StudentRequest;
use App\Http\Requests\UserRequest;
use App\Http\Resources\EnrollmentResource;
use App\Http\Resources\StudentResource;
use App\Models\Student;
use App\Services\EnrollmentService;

use App\Services\FileStorageService;

class StudentAuthController extends Controller
{
    use AppHelpers;

    private PeruDevService $peruDevService;
    private EnrollmentService $enrollmentService;

    public function __construct(
        PeruDevService $peruDevService,
        EnrollmentService $enrollmentService
    ) {
        $this->peruDevService = $peruDevService;
        $this->enrollmentService = $enrollmentService;
    }

    // Verificar si estudiante existe en BD o consultar RENIEC
    public function checkStudent(StudentRequest $request): JsonResponse
    {
        $documentType = $request->input('document_type');
        $documentNumber = $request->input('document_number');

        // Buscar en base de datos primero
        $student = Student::where('document_type', $documentType)
            ->where('document_number', $documentNumber)
            ->first();

        if ($student) {
            return response()->json([
                'success' => true,
                'message' => 'Estudiante encontrado en sistema',
                'data' => [
                    'document_type' => $student->document_type->value,
                    'document_number' => $student->document_number,
                    'names' => $student->names,
                    'paternal_surname' => $student->paternal_surname,
                    'maternal_surname' => $student->maternal_surname,
                    'birth_date' => $student->birth_date,
                    'gender' => $student->gender->value,
                    'email' => $student->email,
                    'phone_number' => $student->phone_number,
                    'whatsapp_number' => $student->whatsapp_number,
                ],
                'source' => 'database',
            ], 200);
        }

        // Si es DNI y no está en BD, consultar RENIEC
        if ($documentType === DocumentType::DNI->value) {
            $apiResponse = $this->peruDevService->getPersonByDni($documentNumber);
            $apiResponse['source'] = 'reniec';
            return response()->json($apiResponse);
        }

        // No encontrado en ningún lado
        return response()->json([
            'success' => false,
            'message' => 'Documento no encontrado en el sistema',
        ], 404);
    }

    // Registrar estudiante y crear matrícula
    public function register(StudentRequest $request)
    {
        // REGLA 1: Validar que exista ciclo activo
        $cycle = $this->getActiveCycle();

        // REGLA 2: Validar que las inscripciones estén abiertas
        if (!$cycle->enrollment_open) {
            return response()->json([
                'success' => false,
                'message' => 'El proceso de inscripciones está cerrado.',
            ], 403);
        }

        // Crear o actualizar estudiante con matrícula
        $result = $this->enrollmentService->registerStudentWithEnrollment($request->all(), $cycle);

        if (!$result['success']) {
            return auth_response_error($result['message'], 400);
        }

        $student = $result['student'];
        $enrollment = $result['enrollment'];
        $message = $result['message'];

        return auth_response_success(
            user: $student->toArray(),
            token: $student->plain_token,
            tokenExpires: $student->token_expires_at,
            meta: [
                'enrollment' => $enrollment->toArray(),
                'registration_steps' => $enrollment->getCompletedSteps(),
                'is_registration_completed' => $enrollment->isCompleted(),
            ],
            message: $message
        );
    }

    // Iniciar sesión
    public function login(StudentRequest $request)
    {
        $validated = $request->validated();

        // 1. Buscar estudiante
        $student = Student::findByOrAbort(
            'document_number',
            $validated['document_number'],
            'Estudiante no encontrado.'
        );

        // 2. REGLA 1: Validar que exista ciclo activo
        $cycle = $this->getActiveCycle();

        // 3. Obtener matrícula activa
        $activeEnrollment = $this->getActiveEnrollment($student);

        // 4. REGLA 2: Si el ciclo está cerrado y NO completó pasos -> ERROR
        if (!$cycle->enrollment_open && !$activeEnrollment->isCompleted()) {
            return response()->json([
                'success' => false,
                'message' => 'El proceso de matrícula está cerrado.',
            ], 403);
        }

        // 5. AHORA SÍ validar credenciales
        if (!$student->checkPassword($validated['password'])) {
            return response()->json([
                'success' => false,
                'message' => 'Credenciales inválidas.',
            ], 404);
        }

        // 6. Generar token y actualizar último acceso
        $student->generateAccessToken(2);
        $student->updateLastLogin();

        // 7. Respuesta exitosa
        return auth_response_success(
            user: $student->toArray(),
            token: $student->plain_token,
            tokenExpires: $student->token_expires_at,
            meta: [
                'enrollment' => $activeEnrollment->load('payments')->toArray(),
                'registration_steps' => $activeEnrollment->getCompletedSteps(),
                'is_registration_completed' => $activeEnrollment->isCompleted(),
            ],
            message: 'Inicio de sesión exitoso'
        );
    }

    // Cerrar sesión
    public function logout(Request $request): JsonResponse
    {
        $student = $request->user();
        $student->invalidateToken();

        return response()->json([
            'message' => 'Sesión cerrada exitosamente',
            'success' => true
        ]);
    }

    // Cambiar password
    public function changePassword(UserRequest $request): StudentResource
    {
        $student = $request->user();

        $validated = $request->validated();

        $student->update(['password' => $validated['password']]);

        return StudentResource::make($student)->additional([
            'success' => true,
            'message' => 'Password actualizado exitosamente',
        ]);
    }

    // Perfil -- falta revisar
    public function profile(Request $request)
    {
        $student = $request->user();
        $activeEnrollment = $student->latestEnrollmentActive;

        // $data = $this->buildStudentAuthData($student, $activeEnrollment);

        // return response()->json([
        //     'success' => true,
        //     'data' => $data,
        //     'message' => 'Perfil obtenido exitosamente',
        // ]);
    }

    // Actualizar perfil -- falta revisar
    public function updateProfile(Request $request): JsonResponse
    {
        // TODO: Implementar actualización de perfil
        return response()->json(['message' => 'Update profile - Por implementar']);
    }
}
