<?php

namespace Kylin\AntiAddiction\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Kylin\AntiAddiction\Enums\AgeGroup;
use Kylin\Core\Models\BaseModel;

/**
 * 消费记录模型
 *
 * 记录未成年人的充值消费行为，用于月度消费限额计算。
 * 金额单位统一为分（1 元 = 100 分）。
 *
 * @property int $id
 * @property int $user_id
 * @property int $game_id
 * @property int $amount_cents       消费金额（分）
 * @property string $order_no        订单号
 * @property string $status          状态：pending/success/failed/refunded
 * @property AgeGroup $age_group_at_time 消费时的年龄分组
 */
class SpendingRecord extends BaseModel
{
    protected $table = 'kylin_spending_records';

    protected $fillable = [
        'user_id',
        'game_id',
        'amount_cents',
        'order_no',
        'status',
        'age_group_at_time',
    ];

    protected $casts = [
        'age_group_at_time' => AgeGroup::class,
    ];

    protected $attributes = [
        'status' => 'pending',
    ];

    /**
     * 关联用户
     */
    public function user(): BelongsTo
    {
        $userModel = config('kylin-anti-addiction.models.user', \Kylin\User\Models\User::class);

        return $this->belongsTo($userModel);
    }

    /**
     * 获取用户当月成功消费总额（分）
     */
    public static function monthlyTotal(int $userId): int
    {
        return static::where('user_id', $userId)
            ->where('status', 'success')
            ->whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->sum('amount_cents');
    }

    /**
     * 标记支付成功
     */
    public function markSuccess(): void
    {
        $this->update(['status' => 'success']);
    }

    /**
     * 标记支付失败
     */
    public function markFailed(): void
    {
        $this->update(['status' => 'failed']);
    }

    /**
     * 标记已退款
     */
    public function markRefunded(): void
    {
        $this->update(['status' => 'refunded']);
    }
}
