import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { UserServiceMt } from '../services/user.service.mt';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { CreateUserDtoMt, UpdateUserDtoMt, UserSchemaMt } from '../schemas/user.schema.mt';
import { parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';

// 创建多租户用户路由 - 自定义业务逻辑（密码加密等）
const createUserRouteMt = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateUserDtoMt }
      }
    }
  },
  responses: {
    201: {
      description: '用户创建成功',
      content: {
        'application/json': { schema: UserSchemaMt }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建用户失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新多租户用户路由 - 自定义业务逻辑
const updateUserRouteMt = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '用户ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: UpdateUserDtoMt }
      }
    }
  },
  responses: {
    200: {
      description: '用户更新成功',
      content: {
        'application/json': { schema: UserSchemaMt }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '更新用户失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除多租户用户路由 - 自定义业务逻辑
const deleteUserRouteMt = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '用户ID'
      })
    })
  },
  responses: {
    204: { description: '用户删除成功' },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '用户不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除用户失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(createUserRouteMt, async (c) => {
    try {
      const data = c.req.valid('json');
      const userService = new UserServiceMt(AppDataSource);

      // 从认证上下文中获取租户ID
      const tenantId = c.get('tenantId');
      const result = await userService.createUser(data, tenantId);

      return c.json(await parseWithAwait(UserSchemaMt, result), 201);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      // 处理用户名重复错误
      if (error instanceof Error && error.message.includes('用户名已存在')) {
        return c.json({
          code: 400,
          message: '用户名已存在'
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建用户失败'
      }, 500);
    }
  })
  .openapi(updateUserRouteMt, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const data = c.req.valid('json');
      const userService = new UserServiceMt(AppDataSource);

      // 从认证上下文中获取租户ID
      const tenantId = c.get('tenantId');
      const result = await userService.updateUser(id, data, tenantId);

      if (!result) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      return c.json(await parseWithAwait(UserSchemaMt, result), 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新用户失败'
      }, 500);
    }
  })
  .openapi(deleteUserRouteMt, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const userService = new UserServiceMt(AppDataSource);

      // 从认证上下文中获取租户ID
      const tenantId = c.get('tenantId');
      const success = await userService.deleteUser(id, tenantId);

      if (!success) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      return c.body(null, 204);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除用户失败'
      }, 500);
    }
  });

export default app;