<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\IndexQueryRequest;
use App\Http\Requests\PermissionRequest;
use App\Http\Resources\PermissionResource;
use App\Models\Permission;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PermissionController extends Controller
{

    private array $messages = [
        'index'          => 'Lista de Permisos obtenidos exitosamente',
        'store'          => 'Permiso creado exitosamente',
        'show'           => 'Permiso obtenido exitosamente',
        'update'         => 'Permiso actualizado exitosamente',
        'destroy'        => 'Permiso eliminado exitosamente',
        'not_found'      => 'Permiso no encontrado',
        'cannot_destroy' => 'No se puede eliminar el Permiso porque tiene provincias asignadas',
    ];

    public function index(IndexQueryRequest $request): JsonResponse
    {
        $items = Permission::query()
            ->included()
            ->search()
            ->filter()
            ->sort()
            ->paginated();

        return PermissionResource::collection($items)
            ->additional([
                'success' => true,
                'message' => $this->messages['index']
            ])
            ->response();
    }

    public function store(PermissionRequest $request): JsonResponse
    {
        $item = Permission::create($request->validated());

        return PermissionResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['store']
            ])
            ->response()
            ->setStatusCode(201);
    }

    public function show(int $id): JsonResponse
    {
        $item = Permission::findOrAbort($id, $this->messages['not_found']);

        return PermissionResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['show']
            ])
            ->response();
    }

    public function update(PermissionRequest $request, int $id): JsonResponse
    {
        $item = Permission::findOrAbort($id, $this->messages['not_found']);
        $item->update($request->validated());

        return PermissionResource::make($item)
            ->additional([
                'success' => true,
                'message' => $this->messages['update']
            ])
            ->response();
    }

    public function destroy(int $id): JsonResponse
    {
        try {
            $item = Permission::findOrAbort($id, $this->messages['not_found']);
            $item->delete();

            return PermissionResource::make($item)
                ->additional([
                    'success' => true,
                    'message' => $this->messages['destroy']
                ])
                ->response();
        } catch (QueryException $e) {
            // Foreign key constraint violation
            if ($e->getCode() === '23000') {
                return response()->json([
                    'success' => false,
                    'message' => $this->messages['cannot_destroy']
                ], 409);
            }

            // Re-lanzar otros errores para que el handler global los maneje
            throw $e;
        }
    }


    // Obtener todos los grupos de permisos 
    public function groups(): JsonResponse
    {
        $groups = Permission::select('group')
            ->distinct()
            ->orderBy('group')
            ->pluck('group');

        return response()->json([
            'success' => true,
            'data' => $groups,
        ]);
    }

    // Activar o desactivar un permiso
    public function toggleStatus(int $id): PermissionResource
    {

        $permission = Permission::findOrAbort($id, $this->messages['not_found']);

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

        return PermissionResource::make($permission)->additional([
            'success' => true,
            'message' => 'Permiso actualizado exitosamente',
        ]);
    }
}
