<?php

namespace App\Http\Controllers\v1\Tenancy\PromoCode;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProductPromoCodeDiscountRequest;
use App\Models\Tenancy\Loyalty;
use App\Models\Tenancy\UserPromoCode;
use App\Models\Tenancy\Warehouse;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;

class GetProductPromoCodeDiscounts extends Controller
{
    /**
     * @throws ValidationException
     */
    public function __invoke(ProductPromoCodeDiscountRequest $request): Response
    {
        $promoCode = Loyalty::ofType('promo_code')
            ->where('promo_code', $request->promo_code)
            ->active()
            ->with('productDiscounts')
            ->firstOrFail();

        $userHasPromoCode = UserPromoCode::ofClient($request->client_unique_id)
            ->where('loyalty_id', $promoCode->id)
            ->first();

        if ($userHasPromoCode) {
            throw ValidationException::withMessages([
                'promo_code' => 'Promo code is already used',
            ]);
        }

//        UserPromoCode::create([
//            'loyalty_id' => $promoCode->id,
//            'client_unique_id' => $request->client_unique_id,
//        ]);
        $productsIds = Warehouse::byProductCodes($request->products)->pluck('id')->toArray();
        $discountedProducts = [];
        foreach ($promoCode->productDiscounts as $discount) {
            if (in_array($discount->product_id, $productsIds)) {
                $discountedProducts[$discount->product_id] = $discount->discount;
            }
        }
        $productsToDiscount = Warehouse::whereIn('id', array_keys($discountedProducts))->get();
        foreach ($productsToDiscount as $product) {
            $product->realization_price = $product->realization_price * (100 - $discountedProducts[$product->id]) / 100;
        }

        return $this->ok($productsToDiscount);
    }
}
