import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';
import { AggregatedService } from '../services/aggregated.service';
import {
  CreateAggregatedDisabledPersonSchema,
  AggregatedDisabledPersonSchema
} from '../schemas/disabled-person.schema';

// 创建聚合残疾人信息路由（包含所有关联数据）
const createAggregatedDisabledPersonRoute = createRoute({
  method: 'post',
  path: '/createAggregatedDisabledPerson',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateAggregatedDisabledPersonSchema }
      }
    }
  },
  responses: {
    200: {
      description: '聚合残疾人信息创建成功',
      content: {
        'application/json': { schema: AggregatedDisabledPersonSchema }
      }
    },
    400: {
      description: '参数错误或身份证号已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建聚合残疾人信息失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取聚合残疾人信息路由（包含所有关联数据）
const getAggregatedDisabledPersonRoute = createRoute({
  method: 'get',
  path: '/getAggregatedDisabledPerson/{id}',
  middleware: [authMiddleware],
  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: AggregatedDisabledPersonSchema.nullable() }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '残疾人不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取聚合残疾人信息失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新聚合残疾人信息路由（包含所有关联数据）
const updateAggregatedDisabledPersonRoute = createRoute({
  method: 'put',
  path: '/updateAggregatedDisabledPerson/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '残疾人ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: CreateAggregatedDisabledPersonSchema }
      }
    }
  },
  responses: {
    200: {
      description: '聚合残疾人信息更新成功',
      content: {
        'application/json': { schema: AggregatedDisabledPersonSchema }
      }
    },
    400: {
      description: '参数错误或身份证号已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '残疾人不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '更新聚合残疾人信息失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 创建聚合残疾人信息
  .openapi(createAggregatedDisabledPersonRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const aggregatedService = new AggregatedService(AppDataSource);

      const result = await aggregatedService.createDisabledPersonWithAllData(data);

      return c.json(await parseWithAwait(AggregatedDisabledPersonSchema, result), 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: 400,
          message: '身份证号已存在'
        }, 400);
      }

      // 处理文件验证错误
      if (error instanceof Error && (error.message.includes('文件验证失败') || error.message.includes('文件ID') || error.message.includes('照片必须包含有效的文件ID'))) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建聚合残疾人信息失败'
      }, 500);
    }
  })
  // 获取聚合残疾人信息
  .openapi(getAggregatedDisabledPersonRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const aggregatedService = new AggregatedService(AppDataSource);

      const result = await aggregatedService.findDisabledPersonWithAllData(id);

      if (!result) {
        return c.json(null, 200);
      }

      const validatedResult = await parseWithAwait(AggregatedDisabledPersonSchema, result);
      return c.json(validatedResult, 200);
    } catch (error) {
      // 处理残疾人不存在错误
      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(updateAggregatedDisabledPersonRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const data = c.req.valid('json');
      const aggregatedService = new AggregatedService(AppDataSource);

      const result = await aggregatedService.updateDisabledPersonWithAllData(id, data);

      if (!result) {
        return c.json({ code: 404, message: '残疾人不存在' }, 404);
      }

      return c.json(await parseWithAwait(AggregatedDisabledPersonSchema, result), 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: 400,
          message: '身份证号已存在'
        }, 400);
      }

      // 处理文件验证错误
      if (error instanceof Error && (error.message.includes('文件验证失败') || error.message.includes('文件ID') || error.message.includes('照片必须包含有效的文件ID'))) {
        return c.json({
          code: 400,
          message: error.message
        }, 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);
    }
  });

export default app;