<?php

namespace App\Models;

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

/** 注项明细 {@see ticket_items} */
final class TicketItem extends Model
{
    protected $fillable = [
        'ticket_no',
        'order_id',
        'player_id',
        'draw_id',
        'original_number',
        'normalized_number',
        'play_code',
        'dimension',
        'digit_slot',
        'bet_mode',
        'unit_bet_amount',
        'total_bet_amount',
        'rebate_rate_snapshot',
        'commission_rate_snapshot',
        'actual_deduct_amount',
        'odds_snapshot_json',
        'rule_snapshot_json',
        'combination_count',
        'estimated_max_payout',
        'risk_locked_amount',
        'status',
        'fail_reason_code',
        'fail_reason_text',
        'win_amount',
        'jackpot_win_amount',
        'settled_at',
    ];

    protected function casts(): array
    {
        return [
            'order_id' => 'integer',
            'player_id' => 'integer',
            'draw_id' => 'integer',
            'dimension' => 'integer',
            'digit_slot' => 'integer',
            'unit_bet_amount' => 'integer',
            'total_bet_amount' => 'integer',
            'rebate_rate_snapshot' => 'decimal:4',
            'commission_rate_snapshot' => 'decimal:4',
            'actual_deduct_amount' => 'integer',
            'odds_snapshot_json' => 'json',
            'rule_snapshot_json' => 'json',
            'combination_count' => 'integer',
            'estimated_max_payout' => 'integer',
            'risk_locked_amount' => 'integer',
            'win_amount' => 'integer',
            'jackpot_win_amount' => 'integer',
            'settled_at' => 'datetime',
        ];
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(TicketOrder::class, 'order_id');
    }

    public function player(): BelongsTo
    {
        return $this->belongsTo(Player::class);
    }

    public function draw(): BelongsTo
    {
        return $this->belongsTo(Draw::class);
    }

    public function combinations(): HasMany
    {
        return $this->hasMany(TicketCombination::class, 'ticket_item_id');
    }

    public function latestSettlementDetail(): HasOne
    {
        return $this->hasOne(TicketSettlementDetail::class, 'ticket_item_id')->latestOfMany('id');
    }
}
