<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\UuidService;
use Illuminate\Http\Request;
use App\Helpers\UuidEncryptionHelper;

class UuidController extends Controller
{
    protected $uuidService;

    public function __construct(UuidService $uuidService)
    {
        $this->uuidService = $uuidService;
    }

    /**
     * Verificar que el usuario tenga privilegios de administrador
     */
    protected function authorizeAdmin(Request $request)
    {
        if (!in_array((int)$request->user()->role, [0, 1], true)) {
            abort(403, 'Acceso denegado. Se requieren privilegios de administrador o superadministrador.');
        }
    }

    /**
     * Listar todos los dispositivos UUIDs
     */
    public function index(Request $request)
    {
        $this->authorizeAdmin($request);

        try {
            $searchTerm = $request->input('q');
            $uuids = $this->uuidService->listUuids($searchTerm);

            return response()->json([
                'success' => true,
                'data' => $uuids->items(),
                'meta' => [
                    'current_page' => $uuids->currentPage(),
                    'last_page' => $uuids->lastPage(),
                    'total' => $uuids->total(),
                    'has_more' => $uuids->hasMorePages()
                ],
                'message' => 'Dispositivos recuperados correctamente.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Error al recuperar dispositivos: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Registrar un dispositivo de forma manual o vincularlo
     */
    public function store(Request $request)
    {
        $this->authorizeAdmin($request);

        $request->validate([
            'user_id' => 'required|exists:users,id',
            'uuid' => 'required|string',
            'status' => 'required|in:0,1',
        ]);

        try {
            // Desencriptar el UUID recibido
            $decryptedUuid = UuidEncryptionHelper::decrypt($request->input('uuid'));

            $uuid = $this->uuidService->createUuid([
                'user_id' => $request->input('user_id'),
                'uuid' => $decryptedUuid,
                'status' => $request->input('status')
            ]);

            return response()->json([
                'success' => true,
                'data' => $uuid,
                'message' => 'Dispositivo registrado y vinculado correctamente.'
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * Actualizar estado del dispositivo
     */
    public function update(Request $request, $id)
    {
        $this->authorizeAdmin($request);

        $request->validate([
            'status' => 'required|in:0,1',
        ]);

        try {
            $uuid = $this->uuidService->updateUuid($id, $request->only('status'));

            return response()->json([
                'success' => true,
                'data' => $uuid,
                'message' => 'Estado del dispositivo actualizado correctamente.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Error al actualizar dispositivo: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Eliminar un dispositivo
     */
    public function destroy(Request $request, $id)
    {
        $this->authorizeAdmin($request);

        try {
            $this->uuidService->deleteUuid($id);

            return response()->json([
                'success' => true,
                'message' => 'Dispositivo eliminado correctamente.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Error al eliminar dispositivo: ' . $e->getMessage()
            ], 500);
        }
    }
}
