<?php

namespace App\Models;

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

class GameEnterLog extends Model
{
    const TABLE = 'agent.dbo.game_enter_log';

    protected $table = self::TABLE;

    public $timestamps = false;

    protected $fillable = [
        'user_id',
        'game_id',
        'duration_ms',
        'log_date',
        'created_at',
    ];

    /**
     * Insert detail log and update daily aggregate.
     *
     * @param array $data user_id, game_id, duration_ms, log_date (optional)
     * @return bool
     */
    public static function addLog(array $data)
    {
        $userId = (int) ($data['user_id'] ?? 0);
        $gameId = (int) ($data['game_id'] ?? 0);
        $durationMs = (int) ($data['duration_ms'] ?? 0);
        $logDate = $data['log_date'] ?? date('Y-m-d');

        if ($gameId <= 0 || $durationMs < 0) {
            return false;
        }

        return DB::connection('write')->transaction(function () use ($userId, $gameId, $durationMs, $logDate) {
            $inserted = DB::connection('write')->table(self::TABLE)->insert([
                'user_id' => $userId,
                'game_id' => $gameId,
                'duration_ms' => $durationMs,
                'log_date' => $logDate,
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            if (!$inserted) {
                return false;
            }

            GameEnterDailyStat::incrementStat($gameId, $logDate, $durationMs);

            return true;
        });
    }
}
