<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\PageResource;
use App\Models\Page;
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 PageController extends Controller
{
    public function index()
    {
        Gate::authorize('viewAny', Page::class);

        return PageResource::collection(Page::all());
    }

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

        return new PageResource($page);
    }

    public function show(Page $page)
    {
        Gate::authorize('view', $page);

        return new PageResource($page);
    }

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

        return new PageResource($page);
    }

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

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