<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Http\Controllers\Controller;
use App\Http\Requests\TeacherRequest;
use App\Http\Resources\TeacherResource;
use App\Models\Teacher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class TeacherAuthController extends Controller
{
    private array $messages = [
        'index'          => 'Lista de Docentes obtenidos exitosamente',
        'store'          => 'Estudiante creado exitosamente',
        'show'           => 'Estudiante obtenido exitosamente',
        'update'         => 'Estudiante actualizado exitosamente',
        'destroy'        => 'Estudiante eliminado exitosamente',
        'not_found'      => 'Estudiante no encontrado',
        'cannot_destroy' => 'No se puede eliminar el Estudiante porque esta en uso',
    ];

    // Login
    public function login(TeacherRequest $request): JsonResponse | TeacherResource
    {
        $validated = $request->validated();

        $teacher = $this->findOrFail(Teacher::class, 'document_number', $validated['document_number'], 'Docente no encontrado.');

        $user = Teacher::findByOrAbort('document_number', $validated['document_number'], $this->messages['not_found']);
        // Validar credenciales
        if (!$teacher->checkPassword($validated['password'])) {
            return response()->json([
                'success' => false,
                'message' => 'Credenciales inválidas',
            ], 401);
        }

        // Generar nuevo token de acceso
        $teacher->generateAccessToken(2);
        $teacher->updateLastLogin();

        return auth_response_success(
            user: $teacher->toArray(),
            token: $teacher->plain_token,
            tokenExpires: $teacher->token_expires_at,
            meta: [
                'roles' => $teacher->roles()->pluck('slug')->toArray(),
                'permissions' => $teacher->permissions()->pluck('slug')->toArray()
            ]
        );
    }

    // Logout
    public function logout(Request $request): JsonResponse
    {
        $teacher = $request->user();
        $teacher->invalidateToken();

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