import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, parseWithAwait } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils/schema/error'
import { talentAuthMiddleware } from '@d8d/auth-module';
import { TalentAuthContext, TalentUserBase } from '@d8d/shared-types';
import { OrderService } from '../services/order.service';
import {
  EmploymentStatusResponseSchema,
  EmploymentStatusNullableSchema,
  SalaryRecordsResponseSchema,
  EmploymentHistoryResponseSchema,
  SalaryVideosResponseSchema,
  SalaryQuerySchema,
  EmploymentHistoryQuerySchema,
  SalaryVideoQuerySchema
} from '../schemas/talent-employment.schema';

// 人才用户类型
type TalentUser = TalentUserBase;

/**
 * 获取当前就业状态路由
 */
const getEmploymentStatusRoute = createRoute({
  method: 'get',
  path: '/employment/status',
  middleware: [talentAuthMiddleware],
  responses: {
    200: {
      description: '获取当前就业状态成功(无就业记录时返回null)',
      content: {
        'application/json': { schema: EmploymentStatusNullableSchema }
      }
    },
    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 getSalaryRecordsRoute = createRoute({
  method: 'get',
  path: '/employment/salary-records',
  middleware: [talentAuthMiddleware],
  request: {
    query: SalaryQuerySchema
  },
  responses: {
    200: {
      description: '获取薪资记录成功',
      content: {
        'application/json': { schema: SalaryRecordsResponseSchema }
      }
    },
    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 getEmploymentHistoryRoute = createRoute({
  method: 'get',
  path: '/employment/history',
  middleware: [talentAuthMiddleware],
  request: {
    query: EmploymentHistoryQuerySchema
  },
  responses: {
    200: {
      description: '获取就业历史成功',
      content: {
        'application/json': { schema: EmploymentHistoryResponseSchema }
      }
    },
    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 getSalaryVideosRoute = createRoute({
  method: 'get',
  path: '/employment/salary-videos',
  middleware: [talentAuthMiddleware],
  request: {
    query: SalaryVideoQuerySchema
  },
  responses: {
    200: {
      description: '获取薪资视频成功',
      content: {
        'application/json': { schema: SalaryVideosResponseSchema }
      }
    },
    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<TalentAuthContext>()
  // 获取当前就业状态
  .openapi(getEmploymentStatusRoute, async (c) => {
    try {
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      // 验证person_id是否存在
      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const orderService = new OrderService(AppDataSource);
      const employmentStatus = await orderService.getCurrentEmploymentStatus(personId);

      // 无就业记录时返回null (200状态码)
      if (!employmentStatus) {
        return c.json(null, 200);
      }

      const validatedResult = await parseWithAwait(EmploymentStatusResponseSchema, employmentStatus);
      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(getSalaryRecordsRoute, async (c) => {
    try {
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const query = c.req.valid('query');
      const orderService = new OrderService(AppDataSource);
      const salaryRecords = await orderService.getSalaryRecords(
        personId,
        query.month,
        query.skip ?? 0,
        query.take ?? 10
      );

      const validatedResult = await parseWithAwait(SalaryRecordsResponseSchema, salaryRecords);
      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(getEmploymentHistoryRoute, async (c) => {
    try {
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const query = c.req.valid('query');
      const orderService = new OrderService(AppDataSource);
      const employmentHistory = await orderService.getEmploymentHistory(
        personId,
        query.skip ?? 0,
        query.take ?? 20
      );

      const validatedResult = await parseWithAwait(EmploymentHistoryResponseSchema, employmentHistory);
      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(getSalaryVideosRoute, async (c) => {
    try {
      const user = c.get('user') as TalentUser;
      const personId = user.personId;

      if (!personId) {
        return c.json({
          code: 404,
          message: '用户不存在或未关联残疾人信息'
        }, 404);
      }

      const query = c.req.valid('query');
      const orderService = new OrderService(AppDataSource);
      const salaryVideos = await orderService.getSalaryVideos(
        personId,
        query.assetType,
        query.month,
        query.skip ?? 0,
        query.take ?? 10
      );

      const validatedResult = await parseWithAwait(SalaryVideosResponseSchema, salaryVideos);
      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;
