<?php

namespace App\Http\Controllers;

use App\Models\Restaurante;
use App\Services\PaginatorService;
use App\Services\UuidService;
use App\Exceptions\GenericException;
use App\Exceptions\CantDeleteHasChildException;
use App\Exceptions\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Ramsey\Uuid\Uuid;

class RestaurantesController extends Controller {

    /**
     * Obtiene de forma paginada los restaurantes registrados en el backend
     */
    public function all(Request $request) {
        if($request->user->isGlobalAdmin()) {
            $restaurantes = Restaurante::all();
        } else {
            $restaurantes = $request->user->restaurantes;
        }

        $paginate = app(PaginatorService::class)->paginate(
            perPage: $request->input('per_page', 15),
            page: $request->input('page', 1),
            total: $restaurantes->count(),
            route: 'restaurant.all',
        );

        $data = $restaurantes
            ->skip($paginate['from'] - 1)
            ->take($paginate['per_page'])
            ->all();

        return response()->json([
            'pagination' => $paginate,
            'data' => $data
        ]);
    }

    /**
     * Obtiene un restaurante por su id
     */
    public function get(Request $request, $id) {
        app(UuidService::class)->validOrFail($id);
        $restaurante = Restaurante::findOrFail($id);

        if(!$request->user->isOnRestaurante($restaurante)){
            throw new ModelNotFoundException('restaurante', $restaurante->id);
        }

        return response()->json($restaurante);
    }

    /**
     * Crea un nuevo restaurant
     */
    public function create(Request $request) {
        $this->validate($request, [
            'nombre' => 'required'
        ]);

        $restaurant = Restaurante::create([
            'id' => Uuid::uuid4(),
            'nombre' => $request->input('nombre')
        ]);

        return response()->json($restaurant, 201);
    }

    /**
     * Actualiza un restaurante
     */
    public function update(Request $request, $id) {
        app(UuidService::class)->validOrFail($id);

        $this->validate($request, [
            'nombre' => 'required'
        ]);

        $restaurant = Restaurante::findOrFail($id);

        if(!$request->user->isOnRestaurante($restaurant)){
            throw new ModelNotFoundException('restaurante', $restaurant->id);
        }

        $restaurant->nombre = $request->input('nombre');
        $restaurant->save();

        return response()->json($restaurant);
    }

    /**
     * Elimina un restaurante
     */
    public function delete(Request $request, $id) {
        app(UuidService::class)->validOrFail($id);

        $restaurant = Restaurante::findOrFail($id);

        if($restaurant->canalesVenta()->count() > 0)        throw new CantDeleteHasChildException("restaurant", "canal_venta");
        if($restaurant->categorias()->count() > 0)          throw new CantDeleteHasChildException("restaurant", "categoria");
        if($restaurant->compras()->count() > 0)             throw new CantDeleteHasChildException("restaurant", "compra");
        if($restaurant->usuarios()->count() > 0)            throw new CantDeleteHasChildException("restaurant", "usuario");
        if($restaurant->sectores()->count() > 0)            throw new CantDeleteHasChildException("restaurant", "sector");
        if($restaurant->zonasProduccion()->count() > 0)     throw new CantDeleteHasChildException("restaurant", "zona_produccion");
        if($restaurant->proveedores()->count() > 0)         throw new CantDeleteHasChildException("restaurant", "proveedor");
        if($restaurant->ingredientes()->count() > 0)        throw new CantDeleteHasChildException("restaurant", "ingrediente");
        if($restaurant->productos()->count() > 0)           throw new CantDeleteHasChildException("restaurant", "producto");
        if($restaurant->ventas()->count() > 0)              throw new CantDeleteHasChildException("restaurant", "venta");
        if($restaurant->boletasElectronicas()->count() > 0) throw new CantDeleteHasChildException("restaurant", "boleta_electronica");
        if($restaurant->boletasExentas()->count() > 0)      throw new CantDeleteHasChildException("restaurant", "boleta_exenta");
        if($restaurant->cajas()->count() > 0)               throw new CantDeleteHasChildException("restaurant", "caja");

        $restaurant->delete();
        return response()->json([], 204);
    }
}
