<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Traits\ApiResponse;
use App\Http\Resources\CartItemResource;
use App\Models\CartItem;
use App\Http\Requests\Api\User\StoreCartItemRequest;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use OpenApi\Annotations as OA;

class CartController extends Controller
{
    use ApiResponse;

    /**
     * @OA\Get(
     *     path="/api/user/cart",
     *     summary="Get the user's cart",
     *     tags={"Cart"},
     *     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\Response(
     *         response=200,
     *         description="The user's cart items",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total_items", type="integer", example=1),
     *                 @OA\Property(property="total_price", type="number", format="float", example=100.00),
     *                 @OA\Property(property="items", type="array", @OA\Items(ref="#/components/schemas/CartItemResource"))
     *             ),
     *             @OA\Property(property="message", type="string", example="Cart items retrieved successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     )
     * )
     */
    public function index()
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        $cartItems = $user->cartItems()->with('product.media')->get();
        $response = [
            'total_items' => $cartItems->count(),
            'total_price' => $cartItems->sum(function ($item) {
                return $item->product->price;
            }),
            'items' => CartItemResource::collection($cartItems),

        ];
        return $this->successResponse($response, __('messages.cart_items_retrieved_successfully'));
    }

    /**
     * @OA\Post(
     *     path="/api/user/cart",
     *     summary="Add an item to the cart",
     *     tags={"Cart"},
     *     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\JsonContent(
     *             required={"ids"},
     *             @OA\Property(property="ids", type="object", example="[1, 1, 2, 3]")
     *         )
     *     ),
     *     @OA\Response(
     *         response=201,
     *         description="Item added to cart successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total_items", type="integer", example=1),
     *                 @OA\Property(property="total_price", type="number", format="float", example=100.00),
     *                 @OA\Property(property="items", type="array", @OA\Items(ref="#/components/schemas/CartItemResource"))
     *             ),
     *             @OA\Property(property="message", type="string", example="Item added to cart successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=422,
     *         description="Validation error"
     *     )
     * )
     */
    public function store(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        $data = $request->validate([
            'ids' => 'required|array|min:1',
            'ids.*' => 'required|integer',
        ]);
        $availableProductIds = Product::query()
            ->whereIn('id', $data['ids'])
            ->scopes(['available'])
            ->pluck('id')
            ->toArray();
        $products = [];
        foreach ($data['ids'] as $id) {
            if (in_array($id, $availableProductIds)) {
                $products[] = ['product_id' => $id];
            }
        }
        if (empty($products)) {
            return $this->errorResponse(__('messages.no_available_items_found'), 422);
        }

        $user->cartItems()->createMany($products);
        $cartItems = $user->cartItems()->with('product.media')->get();
        $response = [
            'total_items' => $cartItems->count(),
            'total_price' => $cartItems->sum(function ($item) {
                return $item->product->price;
            }),
            'items' => CartItemResource::collection($cartItems),

        ];
        if (count($products) < count($data['ids'])) {
            return $this->successResponse($response, __('messages.some_items_not_added_to_cart'), 201);
        }
        return $this->successResponse($response, __('messages.item_added_to_cart'), 201);
    }

    /**
     * @OA\Delete(
     *     path="/api/user/cart/{id}",
     *     summary="Remove an item from the cart",
     *     tags={"Cart"},
     *     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,
     *         description="Cart item ID",
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response=204,
     *         description="Item removed from cart successfully",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total_items", type="integer", example=0),
     *                 @OA\Property(property="total_price", type="number", format="float", example=0.00),
     *                 @OA\Property(property="items", type="array", @OA\Items())
     *             ),
     *             @OA\Property(property="message", type="string", example="Item removed from cart successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="Cart item not found"
     *     )
     * )
     */
    public function destroy(CartItem $cartItem)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        if ($cartItem->user_id !== $user->id) {
            return $this->errorResponse(__('messages.cart_item_not_found'), 404);
        }
        $cartItem->delete();

        $cartItems = $user->cartItems()->with('product.media')->get();
        $response = [
            'total_items' => $cartItems->count(),
            'total_price' => $cartItems->sum(function ($item) {
                return $item->product->price;
            }),
            'items' => CartItemResource::collection($cartItems),
        ];

        return $this->successResponse($response, __('messages.item_removed_from_cart'), 200);
    }
}
