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 { DisabledPersonService } from '../services/disabled-person.service';
import {
  WorkHistoryResponseSchema,
  SalaryHistoryResponseSchema,
  CreditInfoResponseSchema,
  PersonVideosResponseSchema,
  CompanyPersonListResponseSchema,
  CompanyPersonListQuerySchema,
  CompanyPersonDetailSchema
} from '../schemas/person-extension.schema';

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

/**
 * 获取人员工作历史路由
 */
const getWorkHistoryRoute = createRoute({
  method: 'get',
  path: '/{id}/work-history',
  middleware: [enterpriseAuthMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取工作历史成功',
      content: {
        'application/json': { schema: WorkHistoryResponseSchema }
      }
    },
    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 getSalaryHistoryRoute = createRoute({
  method: 'get',
  path: '/{id}/salary-history',
  middleware: [enterpriseAuthMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取薪资历史成功',
      content: {
        'application/json': { schema: SalaryHistoryResponseSchema }
      }
    },
    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 getCreditInfoRoute = createRoute({
  method: 'get',
  path: '/{id}/credit-info',
  middleware: [enterpriseAuthMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取征信信息成功',
      content: {
        'application/json': { schema: CreditInfoResponseSchema }
      }
    },
    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 getPersonVideosRoute = createRoute({
  method: 'get',
  path: '/{id}/videos',
  middleware: [enterpriseAuthMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取视频关联成功',
      content: {
        'application/json': { schema: PersonVideosResponseSchema }
      }
    },
    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 getCompanyPersonListRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [enterpriseAuthMiddleware],
  request: {
    query: CompanyPersonListQuerySchema
  },
  responses: {
    200: {
      description: '获取企业人才列表成功',
      content: {
        'application/json': { schema: CompanyPersonListResponseSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取企业人才列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

/**
 * 获取企业专用人才详情路由
 */
const getCompanyPersonDetailRoute = createRoute({
  method: 'get',
  path: '/{id}',
  middleware: [enterpriseAuthMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取企业人才详情成功',
      content: {
        'application/json': { schema: CompanyPersonDetailSchema }
      }
    },
    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(getWorkHistoryRoute, async (c) => {
    try {
      const { id: personId } = c.req.valid('param');

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

      const disabledPersonService = new DisabledPersonService(AppDataSource);

      // 验证人员是否属于该企业
      const isValid = await disabledPersonService.validatePersonBelongsToCompany(personId, companyId);
      if (!isValid) {
        return c.json({
          code: 403,
          message: '权限不足，无法访问该人员数据'
        }, 403);
      }

      const result = await disabledPersonService.getWorkHistory(personId);
      const validatedResult = await parseWithAwait(WorkHistoryResponseSchema, { 工作历史: 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取工作历史失败'
      }, 500);
    }
  })
  // 获取薪资历史
  .openapi(getSalaryHistoryRoute, async (c) => {
    try {
      const { id: personId } = c.req.valid('param');

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

      const disabledPersonService = new DisabledPersonService(AppDataSource);

      // 验证人员是否属于该企业
      const isValid = await disabledPersonService.validatePersonBelongsToCompany(personId, companyId);
      if (!isValid) {
        return c.json({
          code: 403,
          message: '权限不足，无法访问该人员数据'
        }, 403);
      }

      const result = await disabledPersonService.getSalaryHistory(personId);
      const validatedResult = await parseWithAwait(SalaryHistoryResponseSchema, { 薪资历史: 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取薪资历史失败'
      }, 500);
    }
  })
  // 获取征信信息
  .openapi(getCreditInfoRoute, async (c) => {
    try {
      const { id: personId } = c.req.valid('param');

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

      const disabledPersonService = new DisabledPersonService(AppDataSource);

      // 验证人员是否属于该企业
      const isValid = await disabledPersonService.validatePersonBelongsToCompany(personId, companyId);
      if (!isValid) {
        return c.json({
          code: 403,
          message: '权限不足，无法访问该人员数据'
        }, 403);
      }

      const result = await disabledPersonService.getCreditInfo(personId);
      const validatedResult = await parseWithAwait(CreditInfoResponseSchema, { 征信信息: 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取征信信息失败'
      }, 500);
    }
  })
  // 获取视频关联
  .openapi(getPersonVideosRoute, async (c) => {
    try {
      const { id: personId } = c.req.valid('param');

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

      const disabledPersonService = new DisabledPersonService(AppDataSource);

      // 验证人员是否属于该企业
      const isValid = await disabledPersonService.validatePersonBelongsToCompany(personId, companyId);
      if (!isValid) {
        return c.json({
          code: 403,
          message: '权限不足，无法访问该人员数据'
        }, 403);
      }

      const result = await disabledPersonService.getPersonVideos(personId);
      const validatedResult = await parseWithAwait(PersonVideosResponseSchema, { 视频列表: 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取视频关联失败'
      }, 500);
    }
  })
  // 获取企业专用人才列表
  .openapi(getCompanyPersonListRoute, async (c) => {
    try {
      // enterpriseAuthMiddleware 已经验证了用户是企业用户
      const user = c.get('user');
      const companyId = user.companyId!;

      const query = c.req.valid('query');
      const disabledPersonService = new DisabledPersonService(AppDataSource);

      const result = await disabledPersonService.findAllForCompany(companyId, query);
      // 确保page和limit是数字
      const pageNum = Number(query.page) || 1;
      const limitNum = Number(query.limit) || 10;

      const validatedResult = await parseWithAwait(CompanyPersonListResponseSchema, {
        data: result.data,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total: result.total,
          totalPages: Math.ceil(result.total / limitNum)
        }
      });
      return c.json(validatedResult, 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(getCompanyPersonDetailRoute, async (c) => {
    try {
      const { id: personId } = c.req.valid('param');

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

      const disabledPersonService = new DisabledPersonService(AppDataSource);

      const result = await disabledPersonService.findOneForCompany(personId, companyId);
      if (!result) {
        return c.json({
          code: 404,
          message: '人员不存在或不属于该企业'
        }, 404);
      }

      const validatedResult = await parseWithAwait(CompanyPersonDetailSchema, result);
      return c.json(validatedResult, 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);
    }
  });

export default app;