<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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

        return TagResource::collection(Tag::all());
    }

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

        return new TagResource($tag);
    }

    public function show(Tag $tag)
    {
        Gate::authorize('view', $tag);

        return new TagResource($tag);
    }

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

        return new TagResource($tag);
    }

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

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