<?php

declare(strict_types=1);

namespace App\Services\Shop;

use App\Models\Coupon;

class CouponService
{
    public function find(string $code): ?Coupon
    {
        return Coupon::where('code', $code)->first();
    }

    public function apply(?string $code, int $subtotal): array
    {
        if (! $code) return ['discount' => 0, 'free_ship' => false, 'coupon' => null];
        $coupon = $this->find($code);
        if (! $coupon || ! $coupon->isValid($subtotal)) {
            return ['discount' => 0, 'free_ship' => false, 'coupon' => null, 'invalid' => true];
        }
        return [
            'discount' => $coupon->type === 'free_ship' ? 0 : $coupon->computeDiscount($subtotal),
            'free_ship' => $coupon->type === 'free_ship',
            'coupon' => $coupon,
        ];
    }

    public function consume(Coupon $coupon): void
    {
        $coupon->increment('used_count');
    }
}
