<?php

namespace App\Domain\Pricing\Services;

/**
 * One row in the discount picker.
 *
 * The picker never re-derives eligibility — it renders exactly what the engine
 * decided, including WHY something is unavailable. A discount that silently
 * fails to appear generates a phone call to the office.
 */
class DiscountCandidate
{
    public const APPLIED        = 'applied';         // auto-qualified, currently applied
    public const AVAILABLE      = 'available';       // qualifies; replaces the applied one
    public const STACKS         = 'stacks';          // qualifies; adds on top
    public const NEEDS_APPROVAL = 'needs_approval';  // above the actor's ceiling
    public const BLOCKED        = 'blocked';         // cannot apply, with a reason

    public function __construct(
        public readonly int $ruleId,
        public readonly string $name,
        public readonly string $state,
        public readonly ?string $icon = null,
        public readonly ?string $valueLabel = null,
        public readonly int $discountAmount = 0,
        public readonly bool $isStackable = false,
        public readonly bool $isPinned = false,
        public readonly bool $isManual = false,
        public readonly int $displayOrder = 0,
        public readonly ?string $reason = null,
    ) {}

    public function isSelectable(): bool
    {
        return in_array($this->state, [self::AVAILABLE, self::STACKS, self::NEEDS_APPROVAL], true);
    }

    /** Arabic group heading in the picker. */
    public function groupLabel(): string
    {
        return match ($this->state) {
            self::APPLIED        => 'مؤهل تلقائياً',
            self::AVAILABLE      => 'متاح',
            self::STACKS         => 'يُجمع مع غيره',
            self::NEEDS_APPROVAL => 'يحتاج اعتماد',
            default              => 'غير متاح',
        };
    }

    public function toArray(): array
    {
        return [
            'rule_id'        => $this->ruleId,
            'name'           => $this->name,
            'state'          => $this->state,
            'icon'           => $this->icon,
            'value_label'    => $this->valueLabel,
            'discount'       => $this->discountAmount,
            'is_stackable'   => $this->isStackable,
            'is_pinned'      => $this->isPinned,
            'is_manual'      => $this->isManual,
            'display_order'  => $this->displayOrder,
            'reason'         => $this->reason,
            'group_label'    => $this->groupLabel(),
        ];
    }
}
