<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class GameEnterDailyStat extends Model
{
    const TABLE = 'agent.dbo.game_enter_daily_stat';

    protected $table = self::TABLE;

    public $timestamps = false;

    /**
     * Increment daily aggregate for game enter duration.
     */
    public static function incrementStat(int $gameId, string $logDate, int $durationMs): void
    {
        $now = date('Y-m-d H:i:s');
        $updated = DB::connection('write')->table(self::TABLE)
            ->where('game_id', $gameId)
            ->where('log_date', $logDate)
            ->update([
                'enter_count' => DB::raw('enter_count + 1'),
                'total_duration_ms' => DB::raw('total_duration_ms + ' . (int) $durationMs),
                'updated_at' => $now,
            ]);

        if ($updated > 0) {
            return;
        }

        try {
            DB::connection('write')->table(self::TABLE)->insert([
                'game_id' => $gameId,
                'log_date' => $logDate,
                'enter_count' => 1,
                'total_duration_ms' => $durationMs,
                'updated_at' => $now,
            ]);
        } catch (QueryException $e) {
            if (stripos($e->getMessage(), 'duplicate key') === false
                && stripos($e->getMessage(), 'unique') === false) {
                throw $e;
            }
            DB::connection('write')->table(self::TABLE)
                ->where('game_id', $gameId)
                ->where('log_date', $logDate)
                ->update([
                    'enter_count' => DB::raw('enter_count + 1'),
                    'total_duration_ms' => DB::raw('total_duration_ms + ' . (int) $durationMs),
                    'updated_at' => $now,
                ]);
        }
    }
}
