<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\MenuResource;
use App\Models\Menu;
use App\Support\ApiResponse;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;

class MenuController extends Controller
{
    public function index()
    {
        // Gate::authorize('viewAny', Menu::class);
        return MenuResource::collection(Menu::all());
    }

    public function store(Request $request)
    {
        Gate::authorize('create', Menu::class);
        try {
            DB::beginTransaction();
            $item = new Menu;
            $data = $request->all();
            $data['created_by'] = Auth::user()->id;
            $menu = $item->create($data);
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new MenuResource($menu);
    }

    public function show(Menu $menu)
    {
        Gate::authorize('view', $menu);

        return new MenuResource($menu);
    }

    public function update(Request $request, Menu $menu)
    {
        Gate::authorize('update', $menu);
        try {
            DB::beginTransaction();
            $data = $request->all();
            $data['updated_by'] = Auth::user()->id;
            $menu->update($data);
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new MenuResource($menu);
    }

    public function destroy(Menu $menu)
    {
        Gate::authorize('delete', $menu);
        try {
            DB::beginTransaction();
            DB::commit();
        } catch (Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return ApiResponse::success(message: 'با موفقیت حذف شد');
    }
}
