<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

class Voucher extends Model
{
    protected $fillable = [
        'code',
        'type',
        'value',
        'min_purchase',
        'max_discount',
        'usage_limit',
        'usage_count',
        'expires_at',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'expires_at' => 'date',
        'value' => 'float',
        'min_purchase' => 'float',
        'max_discount' => 'float',
        'usage_limit' => 'integer',
        'usage_count' => 'integer',
    ];

    /**
     * Check if the voucher is valid for a given amount.
     */
    public function isValidForPurchase(float $amount): bool
    {
        if (!$this->is_active) {
            return false;
        }

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

        if ($this->usage_limit !== null && $this->usage_count >= $this->usage_limit) {
            return false;
        }

        if ($amount < $this->min_purchase) {
            return false;
        }

        return true;
    }

    /**
     * Calculate discount amount for a given purchase total.
     */
    public function calculateDiscount(float $amount): float
    {
        if (!$this->isValidForPurchase($amount)) {
            return 0.0;
        }

        if ($this->type === 'nominal') {
            return min($this->value, $amount);
        }

        if ($this->type === 'percent') {
            $discount = $amount * ($this->value / 100);
            if ($this->max_discount !== null) {
                $discount = min($discount, $this->max_discount);
            }
            return min($discount, $amount);
        }

        return 0.0;
    }
}
