<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\KeyModel;
use App\Models\SystemModel;

class ConnectController extends Controller
{
    public function index(): void
    {
        $cfg = app_config();
        $this->json([
            'status' => true,
            'web_info' => [
                '_client' => 'Light Year Key System',
                'license' => 'Qp5KSGTquetnUkjX6UVBAURH8hTkZuLM',
                'version' => (string)($cfg['app_version'] ?? '0.0.0'),
                'token_rule' => 'hmac_sha256(game-user_key-serial, token_salt)',
            ],
            'web__dev' => [
                'author' => 'Light Year',
            ],
            'server_time' => time(),
        ]);
    }

    public function indexPost(): void
    {
        $rate = app_rate_limit_consume('legacy_connect_post', 240, 60, app_client_ip());
        if (!empty($rate['limited'])) {
            $this->json(['status' => false, 'reason' => app_zh('请求过于频繁，请稍后再试')]);
            return;
        }

        $in = app_request_data();
        $game = app_clean_text((string)($in['game'] ?? ''), 64);
        $userKey = app_clean_text((string)($in['user_key'] ?? ($in['key'] ?? '')), 128);
        $serialInput = app_clean_text((string)($in['serial'] ?? ''), 128);
        $serialContext = app_resolve_login_device_serial_context($serialInput);
        $serial = (string)($serialContext['serial'] ?? '');

        if ($game === '' || $userKey === '') {
            $this->json(['status' => false, 'reason' => app_zh('参数不足：请传 game 和 user_key')]);
            return;
        }
        if ($serial === '') {
            $this->json(['status' => false, 'reason' => app_zh('设备码（serial）不能为空，浏览器访问会自动绑定当前浏览器')]);
            return;
        }
        $nonce = app_clean_text((string)($in['nonce'] ?? ''), 96);
        if (!app_consume_optional_client_nonce('legacy_connect|' . $game . '|' . $userKey . '|' . app_client_ip(), $nonce, 60)) {
            $this->json(['status' => false, 'reason' => app_zh('请求已重复，请稍后重试')]);
            return;
        }

        $system = (new SystemModel())->get();
        if (($system['mod_status'] ?? 'on') === 'off') {
            $reason = trim((string)($system['maintenance_reason'] ?? app_zh('维护中')));
            $this->json(['status' => false, 'reason' => $reason === '' ? app_zh('维护中') : $reason]);
            return;
        }

        $keyModel = new KeyModel();
        try {
            $consume = $keyModel->consumeLogin($userKey, $game, $serial, (array)($serialContext['aliases'] ?? []));
        } catch (\Throwable $e) {
            $this->json(['status' => false, 'reason' => app_zh('服务器内部错误')]);
            return;
        }
        if (empty($consume['ok'])) {
            $code = (string)($consume['code'] ?? 'KEY_NOT_FOUND');
            app_log_security_event('legacy_connect_failed', [
                'game' => $game,
                'reason' => $code,
            ]);
            $this->json(['status' => false, 'reason' => $this->loginErrorMessage($code)]);
            return;
        }

        $key = (array)($consume['key'] ?? []);
        $nowTs = (int)($consume['server_time'] ?? time());
        $token = token_for($game, $userKey, $serial);
        $tokenV2 = token_v2_for($game, $userKey, $serial);
        app_log_api_event('legacy_connect_success', [
            'game' => $game,
            'serial' => $serial,
            'user_key' => '[redacted]',
        ]);
        $this->json([
            'status' => true,
            'data' => [
                'MOD_NAME' => (string)($system['mod_name'] ?? ''),
                'MOD_STATUS' => (string)($system['notice_status'] ?? ''),
                'FLOTING_TEST' => (string)($system['notice_text'] ?? ''),
                'BHATIA_EXP' => (string)($key['expired_at'] ?? ''),
                'BHATIA_SLOT' => (int)($key['max_devices'] ?? 1),
                'token' => $token,
                'token_v1' => $token,
                'token_v2' => $tokenV2,
                'token_v2_expire' => time() + 900,
                'rng' => $nowTs,
                'serial_used' => $serial,
            ],
        ]);
    }

    private function loginErrorMessage(string $code): string
    {
        if ($code === 'SERIAL_REQUIRED') {
            return app_zh('设备码（serial）不能为空');
        }
        if ($code === 'KEY_DISABLED') {
            return app_zh('卡密已禁用');
        }
        if ($code === 'KEY_EXPIRED') {
            return app_zh('卡密已过期');
        }
        if ($code === 'DEVICE_LIMIT') {
            return app_zh('设备数量已达上限');
        }
        return app_zh('卡密不存在');
    }
}

