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 { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';
import { DisabledPersonService } from '../services/disabled-person.service';
import {
  FindPersonsWithCompanyQuerySchema,
  PersonsWithCompanyResponseSchema
} from '../schemas/disabled-person.schema';

// 查询残疾人与公司关联路由
const findPersonsWithCompanyRoute = createRoute({
  method: 'get',
  path: '/findPersonsWithCompany',
  middleware: [authMiddleware],
  request: {
    query: FindPersonsWithCompanyQuerySchema
  },
  responses: {
    200: {
      description: '获取残疾人企业关联列表成功',
      content: {
        'application/json': { schema: PersonsWithCompanyResponseSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '查询失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 查询残疾人与企业关联信息
  .openapi(findPersonsWithCompanyRoute, async (c) => {
    try {
      const query = c.req.valid('query');
      const disabledPersonService = new DisabledPersonService(AppDataSource);

      const result = await disabledPersonService.findPersonsWithCompany({
        gender: query.gender,
        disabilityType: query.disabilityType,
        disabilityLevel: query.disabilityLevel,
        minAge: query.minAge,
        maxAge: query.maxAge,
        city: query.city,
        district: query.district,
        disabilityId: query.disabilityId,
        companyId: query.companyId,
        page: query.skip ? Math.floor(query.skip / (query.take || 10)) + 1 : 1,
        limit: query.take || 10
      });

      // 验证响应
      const validated = await parseWithAwait(PersonsWithCompanyResponseSchema, result);

      return c.json(validated, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '查询残疾人企业关联失败'
      }, 500);
    }
  });

export default app;
