<?php

namespace App\Http\Controllers\Api\Provider;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Traits\ApiResponse;
use App\Http\Requests\Api\Provider\StoreProductRequest;
use App\Http\Requests\Api\Provider\UpdateProductRequest;
use App\Http\Resources\ProductResource;
use App\Models\Product;
use App\Services\ProductService;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule as ValidationRule;
use OpenApi\Annotations as OA;

class ProductController extends Controller
{
    use ApiResponse;

    protected $productService;

    public function __construct(ProductService $productService)
    {
        $this->productService = $productService;
    }

    /**
     * @OA\Get(
     *     path="/api/provider/products",
     *     summary="Get a list of products for the authenticated provider",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Parameter(
     *         name="type",
     *         in="query",
     *         required=true,
     *         @OA\Schema(type="string", enum={"service", "package"})
     *     ),
     *     @OA\Parameter(
     *         name="is_active",
     *         in="query",
     *         @OA\Schema(type="boolean")
     *     ),
     *     @OA\Parameter(
     *         name="city_id",
     *         in="query",
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="category_id",
     *         in="query",
     *         description="Filter products by a comma-separated list of category IDs",
     *         @OA\Schema(type="string", example="1,2")
     *     ),
     *     @OA\Parameter(
     *         name="per_page",
     *         in="query",
     *         @OA\Schema(type="integer", default=10)
     *     ),
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         @OA\Schema(type="integer", default=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="A list of products",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="array", @OA\Items(oneOf={@OA\Schema(ref="#/components/schemas/ServiceResource"), @OA\Schema(ref="#/components/schemas/PackageResource")})),
     *             @OA\Property(property="message", type="string", example="Products retrieved successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     )
     * )
     */
    public function index(Request $request)
    {
        /** @var \App\Models\ServiceProvider $provider */
        $provider = Auth::user();
        $request->validate([
            'type' => 'required|in:service,package',
            'is_active' => 'sometimes|boolean',
            'city_id' => ['sometimes', 'exists:cities,id'],
            'category_id' => ['nullable', ValidationRule::exists('categories', 'id')->where('is_active', true)],
            'per_page' => 'sometimes|integer|min:1',
            'page' => 'sometimes|integer|min:1',
        ]);

        $products = $provider->products()
            ->with(['media', 'cities', 'category', 'availabilities'])
            ->where('type', $request->type)
            ->when($request->has('is_active'), function ($query) use ($request) {
                $query->where('is_active', $request->is_active);
            })
            ->when($request->has('city_id'), function ($query) use ($request) {
                $query->whereHas('cities', function ($q) use ($request) {
                    $q->where('city_id', $request->city_id);
                });
            })
            ->when($request->category_id, function ($query, $categoryIds) {
                $ids = explode(',', $categoryIds);
                $query->whereIn('category_id', $ids);
            })
            ->paginate($request->get('per_page', 10), ['*'], 'page', $request->get('page', 1));


        return $this->successResponse(ProductResource::collection($products), __('messages.products_retrieved_successfully'));
    }

    /**
     * @OA\Post(
     *     path="/api/provider/products",
     *     summary="Create a new product",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\MediaType(
     *             mediaType="multipart/form-data",
     *             @OA\Schema(
     *                 @OA\Property(property="type", type="string", enum={"service", "package"}),
     *                 @OA\Property(property="name_en", type="string"),
     *                 @OA\Property(property="name_ar", type="string"),
     *                 @OA\Property(property="description_en", type="string"),
     *                 @OA\Property(property="description_ar", type="string"),
     *                 @OA\Property(property="details_en", type="string"),
     *                 @OA\Property(property="details_ar", type="string"),
     *                 @OA\Property(property="price", type="number", format="float"),
     *                 @OA\Property(property="price_before_discount", type="number", format="float"),
     *                 @OA\Property(property="category_id", type="integer"),
     *                 @OA\Property(property="cities[]", type="array", @OA\Items(type="integer")),
     *                 @OA\Property(property="availabilities[]", type="array", @OA\Items(type="string", format="date")),
     *                 @OA\Property(property="images[]", type="array", @OA\Items(type="string", format="binary")),
     *                 @OA\Property(property="videos[]", type="array", @OA\Items(type="string", format="binary")),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="Product created successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", oneOf={@OA\Schema(ref="#/components/schemas/ServiceResource"), @OA\Schema(ref="#/components/schemas/PackageResource")}),
     *             @OA\Property(property="message", type="string", example="Product created successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error"
     *     )
     * )
     */
    public function store(StoreProductRequest $request)
    {
        /** @var \App\Models\ServiceProvider $provider */
        $provider = Auth::user();
        $product = $this->productService->createProduct($request->validated(), $provider);

        return $this->successResponse(new ProductResource($product), __('messages.product_created'), 201);
    }

    /**
     * @OA\Get(
     *     path="/api/provider/products/{id}",
     *     summary="Get a specific product",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Product data",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", oneOf={@OA\Schema(ref="#/components/schemas/ServiceResource"), @OA\Schema(ref="#/components/schemas/PackageResource")}),
     *             @OA\Property(property="message", type="string", example="Product retrieved successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Product not found"
     *     )
     * )
     */
    public function show(Product $product)
    {
        $this->authorize('view', $product);
        $product->load('cities', 'availabilities', 'media', 'category');

        return $this->successResponse(ProductResource::make($product), __('messages.product_retrieved_successfully'));
    }

    /**
     * @OA\Post(
     *     path="/api/provider/products/{id}",
     *     summary="Update a product",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\MediaType(
     *             mediaType="multipart/form-data",
     *             @OA\Schema(
     *                 @OA\Property(property="type", type="string", enum={"service", "package"}),
     *                 @OA\Property(property="name_en", type="string"),
     *                 @OA\Property(property="name_ar", type="string"),
     *                 @OA\Property(property="description_en", type="string"),
     *                 @OA\Property(property="description_ar", type="string"),
     *                 @OA\Property(property="details_en", type="string"),
     *                 @OA\Property(property="details_ar", type="string"),
     *                 @OA\Property(property="price", type="number", format="float"),
     *                 @OA\Property(property="price_before_discount", type="number", format="float"),
     *                 @OA\Property(property="category_id", type="integer"),
     *                 @OA\Property(property="cities[]", type="array", @OA\Items(type="integer")),
     *                 @OA\Property(property="availabilities[]", type="array", @OA\Items(type="string", format="date")),
     *                 @OA\Property(property="images[]", type="array", @OA\Items(type="integer")),
     *                 @OA\Property(property="new_images[]", type="array", @OA\Items(type="string", format="binary")),
     *                 @OA\Property(property="videos[]", type="array", @OA\Items(type="integer")),
     *                 @OA\Property(property="new_videos[]", type="array", @OA\Items(type="string", format="binary")),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Product updated successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", oneOf={@OA\Schema(ref="#/components/schemas/ServiceResource"), @OA\Schema(ref="#/components/schemas/PackageResource")}),
     *             @OA\Property(property="message", type="string", example="Product updated successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Product not found"
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error"
     *     )
     * )
     */
    public function update(UpdateProductRequest $request, Product $product)
    {
        $this->authorize('update', $product);

        $product = $this->productService->updateProduct($request->validated(), $product);


        return $this->successResponse(ProductResource::make($product), __('messages.product_updated'));
    }

    /**
     * @OA\Delete(
     *     path="/api/provider/products/{id}",
     *     summary="Delete a product",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response=204,
     *         description="Product deleted successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="object", example=null),
     *             @OA\Property(property="message", type="string", example="Product deleted successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Product not found"
     *     )
     * )
     */
    public function destroy(Product $product)
    {
        $this->authorize('delete', $product);
        $product->delete();
        return $this->successResponse(null, __('messages.product_deleted'), 204);
    }

    /**
     * @OA\Post(
     *     path="/api/provider/products/{id}/toggle-status",
     *     summary="Toggle the is_active status of a product",
     *     tags={"Provider Products"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Product status toggled successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", oneOf={@OA\Schema(ref="#/components/schemas/ServiceResource"), @OA\Schema(ref="#/components/schemas/PackageResource")}),
     *             @OA\Property(property="message", type="string", example="Product status toggled successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Product not found"
     *     )
     * )
     */
    public function toggleStatus(Product $product)
    {
        $this->authorize('update', $product);
        $product->update(['is_active' => !$product->is_active]);
        return $this->successResponse(ProductResource::make($product), __('messages.product_status_toggled'));
    }
}
