<?php

/**
 * 文件功能：百家乐局次模型
 *
 * 代表一局百家乐游戏，包含骰子结果、局次状态、下注汇总等信息。
 * 提供局次判断和赔率计算的辅助方法。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Models;

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

class BaccaratRound extends Model
{
    protected $fillable = [
        'dice1', 'dice2', 'dice3',
        'total_points', 'result', 'status',
        'bet_opens_at', 'bet_closes_at', 'settled_at',
        'total_bet_big', 'total_bet_small', 'total_bet_triple',
        'total_payout', 'bet_count',
        'bet_count_big', 'bet_count_small', 'bet_count_triple',
    ];

    /**
     * 属性类型转换。
     */
    protected function casts(): array
    {
        return [
            'bet_opens_at' => 'datetime',
            'bet_closes_at' => 'datetime',
            'settled_at' => 'datetime',
            'dice1' => 'integer',
            'dice2' => 'integer',
            'dice3' => 'integer',
            'total_points' => 'integer',
            'total_bet_big' => 'integer',
            'total_bet_small' => 'integer',
            'total_bet_triple' => 'integer',
            'total_payout' => 'integer',
            'bet_count' => 'integer',
            'bet_count_big' => 'integer',
            'bet_count_small' => 'integer',
            'bet_count_triple' => 'integer',
        ];
    }

    /**
     * 该局的所有下注记录。
     */
    public function bets(): HasMany
    {
        return $this->hasMany(BaccaratBet::class, 'round_id');
    }

    /**
     * 判断当前是否在押注时间窗口内。
     */
    public function isBettingOpen(): bool
    {
        return $this->status === 'betting'
            && now()->between($this->bet_opens_at, $this->bet_closes_at);
    }

    /**
     * 计算指定押注类型和金额的预计回报（含本金）。
     *
     * @param  string  $betType  'big' | 'small' | 'triple'
     * @param  int  $amount  押注金额
     * @param  array  $config  游戏配置参数
     */
    public static function calcPayout(string $betType, int $amount, array $config): int
    {
        $payout = match ($betType) {
            'triple' => $amount * ($config['payout_triple'] + 1),
            'big' => $amount * ($config['payout_big'] + 1),
            'small' => $amount * ($config['payout_small'] + 1),
            default => 0,
        };

        return (int) $payout;
    }

    /**
     * 获取结果中文名称。
     */
    public function resultLabel(): string
    {
        return match ($this->result) {
            'big' => '大',
            'small' => '小',
            'triple' => "豹子（{$this->dice1}{$this->dice1}{$this->dice1}）",
            'kill' => '庄家收割',
            default => '未知',
        };
    }

    /**
     * 查询当前正在进行的局次（状态为 betting 且未截止）。
     */
    public static function currentRound(): ?static
    {
        return static::query()
            ->where('status', 'betting')
            ->where('bet_closes_at', '>', now())
            ->latest()
            ->first();
    }
}
