<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\SettingResource;
use App\Models\Setting;
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 SettingController extends Controller
{
    public function index(Request $request)
    {
        $query = Setting::query()->where('is_public', true);

        return SettingResource::collection($query->get());
    }

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

        return new SettingResource($setting);
    }

    public function show(Setting $setting)
    {
        Gate::authorize('view', $setting);

        return new SettingResource($setting);
    }

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

        return new SettingResource($setting);
    }

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

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