import { OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { createRoute } from '@hono/zod-openapi';
import { JWTUtil } from '@d8d/shared-utils';

// 固定的超级管理员账号信息
const SUPER_ADMIN_USERNAME = 'superadmin';
const SUPER_ADMIN_PASSWORD = 'admin123';
const SUPER_ADMIN_ID = 1;

// 登录请求Schema
const LoginSchema = z.object({
  username: z.string().min(1, '用户名不能为空'),
  password: z.string().min(1, '密码不能为空')
}).openapi('LoginRequest');

// 登录响应Schema
const LoginResponseSchema = z.object({
  token: z.string(),
  userId: z.number(),
  username: z.string(),
  message: z.string()
}).openapi('LoginResponse');

// 创建认证路由
const authRoutes = new OpenAPIHono();

// 登录路由
const loginRoute = createRoute({
  method: 'post',
  path: '/login',
  request: {
    body: {
      content: {
        'application/json': {
          schema: LoginSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '登录成功',
      content: {
        'application/json': {
          schema: LoginResponseSchema
        }
      }
    },
    401: {
      description: '用户名或密码错误',
      content: {
        'application/json': {
          schema: z.object({
            message: z.string()
          })
        }
      }
    }
  }
});

authRoutes.openapi(loginRoute, async (c) => {
  const { username, password } = c.req.valid('json');

  // 验证用户名和密码
  if (username !== SUPER_ADMIN_USERNAME || password !== SUPER_ADMIN_PASSWORD) {
    return c.json({ message: '用户名或密码错误' }, 401);
  }

  // 生成JWT token
  const token = JWTUtil.generateToken({
    id: SUPER_ADMIN_ID,
    username: SUPER_ADMIN_USERNAME
  });

  return c.json({
    token,
    userId: SUPER_ADMIN_ID,
    username: SUPER_ADMIN_USERNAME,
    message: '登录成功'
  });
});

export { authRoutes };