<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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

        return LogResource::collection(Log::all());
    }

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

        return new LogResource($log);
    }

    public function show(Log $log)
    {
        Gate::authorize('view', $log);

        return new LogResource($log);
    }

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

        return new LogResource($log);
    }

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

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