<?php

namespace App\Domain\Pricing\Models;

use App\Domain\Pricing\Enums\AdjustmentType;
use App\Domain\Pricing\Enums\PromotionType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Promotion extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes;

    protected $fillable = [
        'academy_id',
        'name_ar',
        'name',
        'description_ar',
        'code',
        'type',
        'adjustment_type',
        'adjustment_value',
        'conditions',
        'target_type',
        'target_id',
        'branch_id',
        'min_purchase_amount',
        'max_discount_amount',
        'start_date',
        'end_date',
        'is_active',
        'usage_limit',
        'usage_count',
        'per_participant_limit',
        'priority',
        'created_by',
        'metadata',
    ];

    protected $casts = [
        'type' => PromotionType::class,
        'adjustment_type' => AdjustmentType::class,
        'adjustment_value' => 'integer',
        'conditions' => 'array',
        'min_purchase_amount' => 'integer',
        'max_discount_amount' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
        'is_active' => 'boolean',
        'usage_limit' => 'integer',
        'usage_count' => 'integer',
        'per_participant_limit' => 'integer',
        'priority' => 'integer',
        'metadata' => 'array',
    ];

    // ─── Relationships ─────────────────────────────────────────────

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\Branch::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\User::class, 'created_by');
    }

    public function usages(): HasMany
    {
        return $this->hasMany(PromotionUsage::class);
    }

    // ─── Scopes ────────────────────────────────────────────────────

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeEffectiveNow(Builder $query): Builder
    {
        $today = now()->toDateString();

        return $query
            ->where('start_date', '<=', $today)
            ->where(function (Builder $q) use ($today) {
                $q->whereNull('end_date')
                    ->orWhere('end_date', '>=', $today);
            });
    }

    public function scopeCoupons(Builder $query): Builder
    {
        return $query->where('type', PromotionType::Coupon->value);
    }

    public function scopeByCode(Builder $query, string $code): Builder
    {
        return $query->where('code', $code);
    }
}
