<?php

namespace App\Domain\Pricing\Models;

use App\Domain\Pricing\Enums\AdjustmentType;
use App\Domain\Pricing\Enums\PricingRuleType;
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\SoftDeletes;
use App\Domain\Shared\Traits\BelongsToBranch;

class PricingRule extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, BelongsToBranch;

    protected $fillable = [
        'academy_id',
        'name_ar',
        'name',
        'description_ar',
        'rule_type',
        'adjustment_type',
        'adjustment_value',
        'conditions',
        'target_type',
        'target_id',
        'branch_id',
        'priority',
        'is_stackable',
        'max_discount_percent',
        'effective_from',
        'effective_to',
        'is_active',
        'usage_limit',
        'usage_count',
        'created_by',
        'metadata',
        'is_pinned',
        'pin_icon',
        'display_order',
        'recipe_key',
        'is_manual',
        'requires_approval',
        'min_role_level',
    ];

    protected $casts = [
        'rule_type' => PricingRuleType::class,
        'adjustment_type' => AdjustmentType::class,
        'adjustment_value' => 'integer',
        'conditions' => 'array',
        'is_stackable' => 'boolean',
        'is_active' => 'boolean',
        'max_discount_percent' => 'integer',
        'priority' => 'integer',
        'usage_limit' => 'integer',
        'usage_count' => 'integer',
        'effective_from' => 'date',
        'effective_to' => 'date',
        'metadata' => 'array',
        'is_pinned' => 'boolean',
        'display_order' => 'integer',
        'is_manual' => 'boolean',
        'requires_approval' => 'boolean',
        'min_role_level' => 'integer',
    ];

    /**
     * Percentage adjustments are stored as basis points. Nothing outside the
     * model should touch the raw column — read and write through these.
     */
    public function getPercentAttribute(): float
    {
        return \App\Domain\Pricing\Support\Percent::fromBasisPoints((int) $this->adjustment_value);
    }

    public function setPercentAttribute(float|int|string $value): void
    {
        $this->attributes['adjustment_value'] = \App\Domain\Pricing\Support\Percent::toBasisPoints($value);
    }

    public function isPercentage(): bool
    {
        return in_array($this->adjustment_type, [
            AdjustmentType::PercentageDiscount,
            AdjustmentType::PercentageIncrease,
        ], true);
    }

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

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

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

    /**
     * A rule targets many branches through the pivot. The legacy single
     * `branch_id` column still works and is treated as one more target.
     */
    public function branches(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(
            \App\Domain\Identity\Models\Branch::class,
            'pricing_rule_branches',
            'pricing_rule_id',
            'branch_id'
        )->withTimestamps();
    }

    /** Branch ids this rule targets, from both the pivot and the legacy column. */
    public function targetBranchIds(): array
    {
        $ids = $this->branches->pluck('id')->all();

        if ($this->branch_id && ! in_array($this->branch_id, $ids, true)) {
            $ids[] = $this->branch_id;
        }

        return $ids;
    }

    public function isAcademyWide(): bool
    {
        return empty($this->targetBranchIds());
    }

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

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

    public function scopeEffectiveOn(Builder $query, $date): Builder
    {
        return $query->where(function (Builder $q) use ($date) {
            $q->whereNull('effective_from')
                ->orWhere('effective_from', '<=', $date);
        })->where(function (Builder $q) use ($date) {
            $q->whereNull('effective_to')
                ->orWhere('effective_to', '>=', $date);
        });
    }

    /**
     * The branch this model is isolated by lives in a pivot, not a column.
     */
    public static function branchScope(): \Illuminate\Database\Eloquent\Scope
    {
        return new \App\Domain\Shared\Scopes\PricingRuleBranchScope();
    }

    /**
     * Read the rules targeting one specific branch, whichever branch is active.
     *
     * Drops the global scope first — without that this would AND the two and
     * silently return only the rules both branches share.
     */
    public function scopeForBranch(Builder $query, ?int $branchId): Builder
    {
        return $query
            ->withoutGlobalScope(\App\Domain\Shared\Scopes\PricingRuleBranchScope::class)
            ->where(function (Builder $q) use ($branchId) {
            // Academy-wide = no legacy FK AND no pivot targeting.
            $q->where(function (Builder $sq) {
                $sq->whereNull('branch_id')->whereNotExists(function ($e) {
                    $e->selectRaw('1')->from('pricing_rule_branches')
                        ->whereColumn('pricing_rule_branches.pricing_rule_id', 'pricing_rules.id');
                });
            });

            if ($branchId) {
                $q->orWhere('branch_id', $branchId)
                    ->orWhereExists(function ($e) use ($branchId) {
                        $e->selectRaw('1')->from('pricing_rule_branches')
                            ->whereColumn('pricing_rule_branches.pricing_rule_id', 'pricing_rules.id')
                            ->where('pricing_rule_branches.branch_id', $branchId);
                    });
            }
        });
    }

    public function scopePinned(Builder $query): Builder
    {
        return $query->where('is_pinned', true)->orderBy('display_order');
    }

    public function scopeAutomatic(Builder $query): Builder
    {
        return $query->where('is_manual', false);
    }

    public function scopeForTarget(Builder $query, ?string $type, ?int $id = null): Builder
    {
        return $query->where(function (Builder $q) use ($type, $id) {
            $q->whereNull('target_type')
                ->orWhere(function (Builder $q2) use ($type, $id) {
                    $q2->where('target_type', $type);
                    if ($id !== null) {
                        $q2->where(function (Builder $q3) use ($id) {
                            $q3->whereNull('target_id')
                                ->orWhere('target_id', $id);
                        });
                    }
                });
        });
    }

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

    public function scopeNonStackable(Builder $query): Builder
    {
        return $query->where('is_stackable', false);
    }
}
