<?php
/**
 * 为登录日志、操作日志补充 dept_id 字段并回填历史数据。
 *
 * 用法（在 server 目录）: php db/run_system_log_dept_id.php
 */
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../support/bootstrap.php';

use support\think\Db;

function systemLogTableHasColumn(string $table, string $column): bool
{
    try {
        $fields = Db::getFields($table);
        return isset($fields[$column]);
    } catch (\Throwable $e) {
        return false;
    }
}

function systemLogIndexExists(string $table, string $indexName): bool
{
    $rows = Db::query("SHOW INDEX FROM `{$table}` WHERE Key_name = ?", [$indexName]);
    return !empty($rows);
}

function addLogDeptColumn(string $table, string $afterColumn): void
{
    if (!systemLogTableHasColumn($table, 'dept_id')) {
        Db::execute(
            "ALTER TABLE `{$table}`
             ADD COLUMN `dept_id` bigint(20) UNSIGNED NULL DEFAULT NULL COMMENT '所属渠道ID' AFTER `{$afterColumn}`"
        );
        echo "OK: {$table} ADD COLUMN dept_id\n";
    } else {
        echo "SKIP: {$table} dept_id column exists\n";
    }

    if (!systemLogIndexExists($table, 'idx_dept_id')) {
        Db::execute("ALTER TABLE `{$table}` ADD INDEX `idx_dept_id` (`dept_id`)");
        echo "OK: {$table} ADD INDEX idx_dept_id\n";
    } else {
        echo "SKIP: {$table} idx_dept_id exists\n";
    }
}

echo "=== system log dept_id migration ===\n";

addLogDeptColumn('sa_system_login_log', 'login_time');
addLogDeptColumn('sa_system_oper_log', 'request_data');

$loginByCreator = Db::execute(
    "UPDATE `sa_system_login_log` l
     INNER JOIN `sa_system_user` u ON u.id = l.created_by
     SET l.dept_id = u.dept_id
     WHERE (l.dept_id IS NULL OR l.dept_id = 0)
       AND u.dept_id IS NOT NULL
       AND u.dept_id > 0"
);
echo "OK: login log backfilled by created_by: {$loginByCreator}\n";

$loginByUsername = Db::execute(
    "UPDATE `sa_system_login_log` l
     INNER JOIN `sa_system_user` u ON u.username = l.username
     SET l.dept_id = u.dept_id
     WHERE (l.dept_id IS NULL OR l.dept_id = 0)
       AND u.dept_id IS NOT NULL
       AND u.dept_id > 0"
);
echo "OK: login log backfilled by username: {$loginByUsername}\n";

$operByUsername = Db::execute(
    "UPDATE `sa_system_oper_log` o
     INNER JOIN `sa_system_user` u ON u.username = o.username
     SET o.dept_id = u.dept_id
     WHERE (o.dept_id IS NULL OR o.dept_id = 0)
       AND u.dept_id IS NOT NULL
       AND u.dept_id > 0"
);
echo "OK: oper log backfilled by username: {$operByUsername}\n";

echo "Done.\n";
