<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Requests\UserRequest;
use App\Http\Resources\UserResource;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{

    private $messages = [
        'index'     => 'Lista de Administradores obtenido exitosamente.',
        'store'     => 'Administrador creado exitosamente.',
        'show'      => 'Administrador obtenido exitosamente.',
        'update'    => 'Administrador actualizado exitosamente.',
        'destroy'   => 'Administrador eliminado exitosamente.',
        'not_found' => 'Administrador no encontrado.',
        'toggle_status'    => 'Estado del Administrador actualizado exitosamente.',
        'reset_password'   => 'Contraseña del Administrador Restablecida exitosamente.',
        'change_password'  => 'Contraseña del Administrador actualizada exitosamente.',
        'sync_roles'       => 'Roles del Administrador actualizados exitosamente.',
    ];

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

        $user = User::findByOrAbort('document_number', $validated['document_number'], $this->messages['not_found']);

        // Validar credenciales
        if (!$user->checkPassword($validated['password'])) {
            return response()->json([
                'success' => false,
                'message' => 'Credenciales inválidas',
            ], 404);
        }

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

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

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

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

    // // Perfil
    // public function profile(Request $request): JsonResponse
    // {
    //     // TODO: Retornar perfil del admin autenticado
    //     return response()->json(['message' => 'Admin profile - Por implementar']);
    // }

    // // Actualizar perfil
    // public function updateProfile(Request $request): JsonResponse
    // {
    //     // TODO: Actualizar perfil del admin
    //     return response()->json(['message' => 'Admin update profile - Por implementar']);
    // }

    // Listar usuarios con búsqueda, ordenamiento y paginación
    public function index(IndexQueryRequest $request)
    {
        $items = User::query()
            ->included()
            ->search()
            ->filter()
            ->sort()
            ->paginated();

        return UserResource::collection($items)->additional([
            'success' => true,
            'message' => 'Usuarios obtenidos exitosamente',
        ]);
    }

    // Crear usuario
    public function store(UserRequest $request): UserResource
    {
        $validated = $request->validated();

        // Contraseña su DNI por defecto
        $validated['password'] = $validated['document_number'];

        $user = User::create($validated);

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => 'Usuario creado exitosamente',
        ]);
    }

    // Ver detalle de un usuario
    public function show(int $id): UserResource
    {
        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => 'Usuario obtenido exitosamente',
        ]);
    }

    // Actualizar usuario
    public function update(UserRequest $request, int $id): UserResource
    {
        $validated = $request->validated();

        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

        $user->update($validated);

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => 'Usuario actualizado exitosamente',
        ]);
    }

    // Eliminar usuario
    public function destroy(int $id): JsonResponse
    {
        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

        // Verificar si tiene roles asignados
        if ($user->roles()->count() > 0) {
            return response()->json([
                'success' => false,
                'message' => 'No se puede eliminar el usuario porque tiene roles asignados',
            ], 400);
        }

        $user->delete();

        return response()->json([
            'success' => true,
            'message' => 'Usuario eliminado exitosamente',
        ]);
    }

    // Activar o desactivar usuario
    public function toggleStatus(int $id): UserResource
    {
        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

        $user->update(['active' => !$user->active]);

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => $this->messages['toggle_status'],
        ]);
    }

    // Restablecer password de usuario
    public function resetPassword(int $id): UserResource
    {
        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

        // Cerrar Sesión 
        $user->invalidateToken();

        $user->update(['password' => $user->document_number]);

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => $this->messages['reset_password'],
        ]);
    }

    // Cambiar Contraseña
    public function changePassword(Request $request, int $id): UserResource
    {
        $validated = $request->validate([
            'password' => ['required', 'string', 'min:8'],
        ], [], [
            'password.required' => 'El password es requerido',
        ]);

        $user = User::included()->findOrAbort($id, $this->messages['not_found']);

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

        return UserResource::make($user)->additional([
            'success' => true,
            'message' => $this->messages['change_password'],
        ]);
    }

    // Sincronizar Roles
    public function syncRoles(Request $request, int $id): JsonResponse | UserResource
    {


        $validated = $request->validate([
            'roles' => 'array',
            'roles.*' => 'exists:roles,slug',
        ], [], [
            'roles' => 'Roles',
        ]);

        $item = User::included()->findOrAbort($id, $this->messages['not_found']);

        try {
            $rolesSlugs = $validated['roles'];
            // Obtener los IDs de los permisos
            $rolesIds = Role::whereIn('slug', $rolesSlugs)
                ->pluck('id')
                ->toArray();

            DB::beginTransaction();
            $item->roles()->sync($rolesIds ?? []);
            DB::commit();

            return UserResource::make($item->load('roles'))->additional([
                'success' => true,
                'message' => $this->messages['sync_roles'],
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Error al sincronizar Roles: ' . $e->getMessage(),
            ], 500);
        }
    }
}
