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 { CompanyOverviewSchema, CompanyTalentResponseSchema } from '../schemas/company-statistics.schema';

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

/**
 * 企业概览统计路由
 */
const companyOverviewRoute = createRoute({
  method: 'get',
  path: '/overview',
  middleware: [enterpriseAuthMiddleware],
  operationId: 'getCompanyOverview',
  responses: {
    200: {
      description: '获取企业概览统计成功',
      content: {
        'application/json': { schema: CompanyOverviewSchema }
      }
    },
    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 companyTalentsRoute = createRoute({
  method: 'get',
  path: '/{id}/talents',
  middleware: [enterpriseAuthMiddleware],
  operationId: 'getCompanyTalents',
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '企业ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取企业维度人才统计成功',
      content: {
        'application/json': { schema: CompanyTalentResponseSchema }
      }
    },
    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(companyOverviewRoute, async (c) => {
    try {
      // enterpriseAuthMiddleware 已经验证了用户是企业用户
      const user = c.get('user');
      const companyId = user.companyId!;

      const companyService = new CompanyService(AppDataSource);
      const result = await companyService.getCompanyOverview(companyId);
      const validatedResult = await parseWithAwait(CompanyOverviewSchema, 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取企业概览统计失败'
      }, 500);
    }
  })
  // 企业维度人才统计
  .openapi(companyTalentsRoute, async (c) => {
    try {
      const { id: requestedCompanyId } = c.req.valid('param');

      // enterpriseAuthMiddleware 已经验证了用户是企业用户
      const user = c.get('user');
      const userCompanyId = user.companyId!;

      // 验证用户是否有权限访问该企业数据
      if (userCompanyId !== requestedCompanyId) {
        return c.json({
          code: 403,
          message: '权限不足，只能访问自己关联的企业数据'
        }, 403);
      }

      const companyService = new CompanyService(AppDataSource);
      const result = await companyService.getCompanyTalents(requestedCompanyId);
      const validatedResult = await parseWithAwait(CompanyTalentResponseSchema, 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: 404,
          message: '企业不存在'
        }, 404);
      }

      // 处理权限错误
      if (error instanceof Error && error.message.includes('权限')) {
        return c.json({
          code: 403,
          message: error.message
        }, 403);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取企业维度人才统计失败'
      }, 500);
    }
  });

export default app;