<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['code', 'type', 'value', 'minimum_order_amount', 'expires_at', 'is_active'])]
class Coupon extends Model
{
    public const TYPE_FIXED = 'fixed';
    public const TYPE_PERCENTAGE = 'percentage';

    protected function casts(): array
    {
        return [
            'value' => 'decimal:2',
            'minimum_order_amount' => 'decimal:2',
            'expires_at' => 'date',
            'is_active' => 'boolean',
        ];
    }

    public function isUsableFor(float $subtotal): bool
    {
        if (! $this->is_active) {
            return false;
        }

        if ($this->expires_at && $this->expires_at->isPast()) {
            return false;
        }

        return $subtotal >= (float) $this->minimum_order_amount;
    }

    public function discountFor(float $subtotal): float
    {
        if (! $this->isUsableFor($subtotal)) {
            return 0.0;
        }

        $discount = $this->type === self::TYPE_PERCENTAGE
            ? $subtotal * ((float) $this->value / 100)
            : (float) $this->value;

        return round(min($subtotal, $discount), 2);
    }
}
