<?php

namespace app\common\model;

use app\common\service\GameHotDataCoordinator;
use support\think\Model;

class GameRecord extends Model
{
    protected $name = 'game_record';

    protected $autoWriteTimestamp = true;

    protected $type = [
        'create_time'             => 'integer',
        'update_time'             => 'integer',
        'period_start_at'         => 'integer',
        'status'                  => 'integer',
        'draw_mode'               => 'integer',
        'result_number'           => 'integer',
        'ai_locked_number'        => 'integer',
        'pending_draw_number'     => 'integer',
        'payout_until'            => 'integer',
        'platform_profit_amount'  => 'string',
        'winner_user_count'      => 'integer',
    ];

    public function setPeriodStartAtAttr($value, $data = [])
    {
        if ($value === null || $value === '') {
            return 0;
        }
        if (is_int($value)) {
            return $value;
        }
        if (is_string($value)) {
            $t = strtotime($value);
            if ($t !== false) {
                return $t;
            }
        }
        return 0;
    }

    public static function onAfterWrite(GameRecord $model): void
    {
        $id = filter_var($model->getAttr('id'), FILTER_VALIDATE_INT);
        GameHotDataCoordinator::afterGameRecordCommitted($id === false ? null : $id);
    }

    public static function onAfterDelete(GameRecord $model): void
    {
        $id = filter_var($model->getAttr('id'), FILTER_VALIDATE_INT);
        GameHotDataCoordinator::afterGameRecordCommitted($id === false ? null : $id);
    }
}
