<?php

/**
 * 文件功能：商店商品模型
 * 对应 shop_items 表，存储商品定义信息
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ShopItem extends Model
{
    public const TYPE_SIGN_REPAIR = 'sign_repair';

    protected $table = 'shop_items';

    protected $fillable = [
        'name', 'slug', 'description', 'icon', 'price',
        'type', 'duration_days', 'duration_minutes', 'sort_order', 'is_active',
        'intimacy_bonus', 'charm_bonus',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    /**
     * 获取该商品的所有购买记录
     */
    public function purchases(): HasMany
    {
        return $this->hasMany(UserPurchase::class);
    }

    /**
     * 是否为自动钓鱼卡
     */
    public function isAutoFishingCard(): bool
    {
        return $this->type === 'auto_fishing';
    }

    /**
     * 是否为签到补签卡。
     */
    public function isSignRepairCard(): bool
    {
        return $this->type === self::TYPE_SIGN_REPAIR;
    }

    /**
     * 是否为特效类商品（instant 或 duration，slug 以 once_ 或 week_ 开头）
     */
    public function isEffect(): bool
    {
        return str_starts_with($this->slug, 'once_') || str_starts_with($this->slug, 'week_');
    }

    /**
     * 是否为周卡（duration 类型）
     */
    public function isWeekCard(): bool
    {
        return $this->type === 'duration';
    }

    /**
     * 是否为单次卡（instant 类型）
     */
    public function isInstant(): bool
    {
        return $this->type === 'instant';
    }

    /**
     * 获取特效 key（去掉 once_ / week_ 前缀，返回 fireworks/rain/lightning/snow）
     */
    public function effectKey(): ?string
    {
        if (str_starts_with($this->slug, 'once_')) {
            return substr($this->slug, 5);
        }
        if (str_starts_with($this->slug, 'week_')) {
            return substr($this->slug, 5);
        }

        return null;
    }

    /**
     * 获取所有上架商品（按排序）
     */
    public static function active(): Collection
    {
        return static::where('is_active', true)->orderBy('sort_order')->get();
    }
}
