<?php

/**
 * 文件功能：创建在职登录记录表迁移
 * 记录职务持有者每次进入聊天室的登录时间、在线时长和登出时间
 * 用于统计在职期间的出勤数据（勤务台四榜 + 个人履历）
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * 创建在职登录记录表
     */
    public function up(): void
    {
        Schema::create('position_duty_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete()
                ->comment('用户 ID');
            $table->foreignId('user_position_id')
                ->constrained('user_positions')
                ->cascadeOnDelete()
                ->comment('关联的在职记录 ID（user_positions.id）');

            $table->timestamp('login_at')->comment('登录/进房时间');
            $table->timestamp('logout_at')->nullable()->comment('退出时间（null=尚未退出）');
            $table->unsignedInteger('duration_seconds')->nullable()->comment('在线时长（秒）');
            $table->string('ip_address', 45)->nullable()->comment('登录 IP');
            $table->unsignedInteger('room_id')->nullable()->comment('进入的房间 ID');

            $table->timestamps();

            // 常用查询索引
            $table->index(['user_position_id', 'login_at']);
            $table->index(['user_id', 'login_at']);
        });
    }

    /**
     * 回滚：删除在职登录记录表
     */
    public function down(): void
    {
        Schema::dropIfExists('position_duty_logs');
    }
};
