import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { enterpriseAuthMiddleware, EnterpriseUserResponseSchema } from '@d8d/auth-module';
import { EnterpriseAuthContext } from '@d8d/shared-types';
import { CompanyService } from '../services/company.service';
import { RecentAllocationsSchema } from '../schemas/company-statistics.schema';

// 企业用户类型
type EnterpriseUser = z.infer<typeof EnterpriseUserResponseSchema>;

/**
 * 近期分配人才查询路由
 */
const companyRecentAllocationsRoute = createRoute({
  method: 'get',
  path: '/allocations/recent',
  middleware: [enterpriseAuthMiddleware],
  operationId: 'getCompanyRecentAllocations',
  request: {
    query: z.object({
      limit: z.coerce.number().int().positive().max(100).optional().openapi({
        param: { name: 'limit', in: 'query' },
        example: 5,
        description: '返回记录数限制，默认5条，最大100条'
      })
    })
  },
  responses: {
    200: {
      description: '获取近期分配人才列表成功',
      content: {
        'application/json': { schema: RecentAllocationsSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足，仅限企业用户访问',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '企业不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取近期分配人才列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<EnterpriseAuthContext>()
  // 近期分配人才查询
  .openapi(companyRecentAllocationsRoute, async (c) => {
    try {
      // enterpriseAuthMiddleware 已经验证了用户是企业用户
      const user = c.get('user');
      const companyId = user.companyId!;

      // 获取查询参数，默认limit为5
      const { limit } = c.req.valid('query');
      const limitValue = limit || 5;

      const companyService = new CompanyService(AppDataSource);
      const result = await companyService.getRecentAllocations(companyId, limitValue);
      const validatedResult = await parseWithAwait(RecentAllocationsSchema, result);
      return c.json(validatedResult, 200);
    } 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: 403,
          message: error.message
        }, 403);
      }

      // 处理企业不存在的情况
      if (error instanceof Error && error.message.includes('企业不存在')) {
        return c.json({
          code: 404,
          message: '企业不存在'
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取近期分配人才列表失败'
      }, 500);
    }
  });

export default app;