<?php

namespace App\libs\middleware;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class ApiLogs
{
    /**
     * 处理传入请求。
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, \Closure $next): Response
    {
        $this->user   = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;
        $data         = $request->all();
        $names        = explode('@', $request->route()->getAction()['controller']);
        $data         = [
            'token'      => $request->header('token', null),
            'user_id'    => $this->userId ?? 0,
            'url'        => $request->url(),
            'controller' => $names[0],
            'func'       => $names[1],
            'method'     => $request->method(),
            'ip'         => $request->ip(),
            'params'     => json_encode($data, 256),
            'day'        => strtotime('today'),
            'created_at' => time(),
        ];
        Db::table('api_logs')->insert($data);

        return $next($request);
    }
}
