<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Shop;

use App\Http\Controllers\Controller;
use App\Services\Shop\CartService;
use App\Services\Shop\CouponService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    public function __construct(
        private readonly CouponService $coupons,
        private readonly CartService $carts,
    ) {}

    public function validateCoupon(Request $request): JsonResponse
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'max:60'],
        ]);
        $cart = $this->carts->resolveCart($request);
        $summary = $this->carts->summary($cart);
        $result = $this->coupons->apply($data['code'], $summary['subtotal']);

        if (! $result['coupon']) {
            return response()->json(['error' => 'COUPON_INVALID'], 422);
        }
        return response()->json([
            'data' => [
                'code' => $result['coupon']->code,
                'type' => $result['coupon']->type,
                'discount' => $result['discount'],
                'free_ship' => $result['free_ship'],
                'subtotal' => $summary['subtotal'],
            ],
        ]);
    }
}
