<?php

namespace App\Http\Controllers;

use App\Models\Service;
use Illuminate\Http\Request;;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\ServiceResource;
use App\Support\ApiResponse;
class ServiceController extends Controller
{
    public function index(Request $request)
    {
        Gate::authorize('viewAny', Service::class);

        $query = Service::query()
            ->with('category')
            ->where('status', 'active')
            ->where('is_active', true);

        $perPage = min($request->integer('per_page', 15), 50);

        return ServiceResource::collection(
            $request->boolean('noPaginate') ? $query->get() : $query->paginate($perPage)
        );
    }

    public function store(Request $request)
    {
        Gate::authorize('create', Service::class);
        try {
            DB::beginTransaction();
            DB::commit();
        } catch (\Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }
        return new ServiceResource($service);
    }

    public function show(Service $service)
    {
        Gate::authorize('view', $service);
        return new ServiceResource($service);
    }

    public function update(Request $request, Service $service)
    {
        Gate::authorize('update', $service);
        try {
            DB::beginTransaction();
            DB::commit();
        } catch (\Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }
        return new ServiceResource($service);
    }

    public function destroy(Service $service)
    {
        Gate::authorize('delete', $service);
        try {
            DB::beginTransaction();
            DB::commit();
        } catch (\Exception $exception) {
            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }
        return ApiResponse::success(message: 'با موفقیت حذف شد');
    }
}
