<?php

use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (ValidationException $exception, Request $request) {
            if (! $request->expectsJson()) {
                return null;
            }

            $attributeLabels = [
                'name' => '名称',
                'display_name' => '显示名称',
                'category' => '分类',
                'description' => '描述',
                'guard_name' => '守卫',
                'parent_id' => '所属服务器',
                'internal_ip' => '内网IP',
                'asset_id' => '资产ID',
                'account_id' => '账号ID',
                'protocol' => '协议',
                'protocols' => '协议',
                'is_active' => '启用状态',
                'nickname' => '昵称',
                'email' => '邮箱',
                'phone' => '手机号',
                'password' => '密码',
                'role_ids' => '角色',
                'permission_ids' => '权限',
                'users' => '用户',
                'from' => '开始日期',
                'to' => '结束日期',
                'action' => '动作',
                'actions' => '动作',
                'user_id' => '用户',
                'user_ids' => '用户',
                'server_resource_id' => '资源',
                'server_resource_ids' => '资源',
                'per_page' => '每页数量',
                'username' => '用户名',
                'token' => '令牌',
            ];

            $resolveAttribute = function (string $field) use ($attributeLabels): string {
                if (isset($attributeLabels[$field])) {
                    return $attributeLabels[$field];
                }

                foreach ($attributeLabels as $key => $label) {
                    if (str_starts_with($field, $key.'.')) {
                        return $label;
                    }
                }

                return $field;
            };

            $ruleMessage = function (string $rule, string $attribute, array $params = []): string {
                return match (strtolower($rule)) {
                    'required' => $attribute.'不能为空',
                    'present' => $attribute.'必须传入',
                    'array' => $attribute.'必须是数组',
                    'string' => $attribute.'必须是字符串',
                    'integer' => $attribute.'必须是整数',
                    'boolean' => $attribute.'必须是布尔值',
                    'email' => $attribute.'格式不正确',
                    'ip' => $attribute.'格式不正确',
                    'date' => $attribute.'必须是有效日期',
                    'exists' => $attribute.'不存在或已失效',
                    'unique' => $attribute.'已存在，请更换',
                    'in' => $attribute.'不在允许范围内',
                    'min' => $attribute.'不能小于'.($params[0] ?? '').'',
                    'max' => $attribute.'不能大于'.($params[0] ?? '').'',
                    'regex' => $attribute.'格式不正确',
                    'nullable' => $attribute.'格式不正确',
                    'sometimes' => $attribute.'格式不正确',
                    default => $attribute.'参数不合法',
                };
            };

            $failedRules = $exception->validator->failed();
            $translatedErrors = [];

            foreach ($failedRules as $field => $rules) {
                $attribute = $resolveAttribute($field);
                foreach ($rules as $rule => $params) {
                    $translatedErrors[$field][] = $ruleMessage($rule, $attribute, $params);
                }
            }

            if (empty($translatedErrors)) {
                $translatedErrors = $exception->errors();
            }

            return response()->json([
                'code' => 422,
                'message' => '请求参数校验失败',
                'errors' => $translatedErrors,
                'data' => null,
            ], 422);
        });

        $exceptions->render(function (UnauthorizedException $exception, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'code' => 403,
                    'message' => '无权限执行此操作',
                    'data' => null,
                ], 403);
            }
        });

        $exceptions->render(function (AuthenticationException $exception, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'code' => 401,
                    'message' => '未认证或登录已过期',
                    'data' => null,
                ], 401);
            }
        });
    })->create();
