<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\ProductResource;
use App\Models\Comment;
use App\Models\Product;
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 ProductController extends Controller
{
    public function index(Request $request)
    {
        Gate::authorize('viewAny', Product::class);

        $query = Product::query()
            ->with(['producer.user', 'category', 'breed'])
            ->where('status', 'active')
            ->where('is_active', true);

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->integer('category_id'));
        }

        if ($request->filled('producer_id')) {
            $query->where('producer_id', $request->integer('producer_id'));
        }

        if ($request->filled('q')) {
            $search = $request->string('q');
            $query->where('name', 'like', "%{$search}%");
        }

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

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

    public function store(Request $request)
    {
        Gate::authorize('create', Product::class);
        try {
            DB::beginTransaction();
            $data = $request->all();
            $data['created_by'] = Auth::id();
            $product = Product::create($data);
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new ProductResource($product->load(['producer.user', 'category', 'breed']));
    }

    public function show(Product $product)
    {
        Gate::authorize('view', $product);

        return new ProductResource(
            $product->load([
                'producer.user',
                'category',
                'breed',
                'province',
                'county',
                'ratings' => fn ($query) => $query->with('user')->latest(),
                'comments' => fn ($query) => $query
                    ->where('status', Comment::STATUS_APPROVED)
                    ->whereNull('parent_id')
                    ->with([
                        'user',
                        'replies' => fn ($replies) => $replies
                            ->where('status', Comment::STATUS_APPROVED)
                            ->with('user')
                            ->latest(),
                    ])
                    ->latest(),
            ])
        );
    }

    public function update(Request $request, Product $product)
    {
        Gate::authorize('update', $product);
        try {
            DB::beginTransaction();
            $data = $request->all();
            $data['updated_by'] = Auth::id();
            $product->update($data);
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

        return new ProductResource($product->fresh()->load(['producer.user', 'category', 'breed']));
    }

    public function destroy(Product $product)
    {
        Gate::authorize('delete', $product);
        try {
            DB::beginTransaction();
            $product->delete();
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();

            return ApiResponse::response(message: $exception->getMessage(), status: 419);
        }

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