<?php
/**
 * Webman 入口文件
 */

require_once __DIR__ . '/../vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

// 启动Webman
require_once __DIR__ . '/../support/bootstrap.php';

\Workerman\Worker::$pidFile = runtime_path() . '/webman.pid';
\Workerman\Worker::$logFile = runtime_path() . '/webman.log';
\Workerman\Worker::$stdoutFile = runtime_path() . '/stdout.log';

$http = new \Workerman\Worker('http://0.0.0.0:8787');
$http->name = config('app.name', '人情备忘助手');
$http->count = cpu_count() * 2;
$http->onWorkerStart = function ($worker) {
    // 加载路由
    require_once config_path() . '/route.php';
};

$http->onMessage = function ($connection, $request) {
    try {
        $response = app()->handle($request);
        $connection->send($response);
    } catch (\Throwable $e) {
        $connection->send(json([
            'code' => 500,
            'message' => '服务器内部错误',
            'data' => null,
            'timestamp' => time(),
        ]));
    }
};

\Workerman\Worker::runAll();
