import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { ErrorSchema } from '@d8d/shared-utils';
import { authMiddleware } from '../middleware/index';
import { AuthContext } from '@d8d/shared-types';
import { EnterpriseUserResponseSchema } from '../schemas/index';
import { AppDataSource } from '@d8d/shared-utils';
import { UserService } from '@d8d/core-module/user-module';
import { parseWithAwait } from '@d8d/shared-utils';

const enterpriseMeRoute = createRoute({
  method: 'get',
  path: '/me',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '获取企业用户信息成功',
      content: {
        'application/json': {
          schema: EnterpriseUserResponseSchema
        }
      }
    },
    401: {
      description: '未授权',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    403: {
      description: '非企业用户',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(enterpriseMeRoute, async (c) => {
  try {
    const user = c.get('user');
    if (!user) {
      return c.json({ code: 401, message: '未授权' }, 401);
    }

    // 验证用户是否是企业用户
    if (!user.companyId) {
      return c.json({ code: 403, message: '非企业用户' }, 403);
    }

    // 加载包含企业详情的用户信息
    const userService = new UserService(AppDataSource);
    const userWithCompany = await userService.getUserWithCompany(user.id);

    if (!userWithCompany) {
      // 用户通过了认证但数据库中不存在，可能是数据不一致
      console.error(`User ${user.id} passed authentication but not found in database`);
      return c.json({ code: 500, message: '获取用户信息失败' }, 500);
    }

    return c.json(await parseWithAwait(EnterpriseUserResponseSchema, userWithCompany), 200);
  } catch (error) {
    console.error('获取企业用户信息失败:', error);
    return c.json({ code: 500, message: '获取用户信息失败' }, 500);
  }
});

export default app;