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 { CompanyService } from '../services/company.service';
import {
  CreateCompanySchema,
  UpdateCompanySchema,
  DeleteCompanySchema,
  CompanySchema,
  PaginationQuerySchema,
  SearchCompanyQuerySchema
} from '../schemas/company.schema';

// 创建公司路由 - 返回布尔值
const createCompanyRoute = createRoute({
  method: 'post',
  path: '/createCompany',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateCompanySchema }
      }
    }
  },
  responses: {
    200: {
      description: '公司创建成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误或公司名称在该平台下已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建公司失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除公司路由 - 返回布尔值
const deleteCompanyRoute = createRoute({
  method: 'post',
  path: '/deleteCompany',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: DeleteCompanySchema }
      }
    }
  },
  responses: {
    200: {
      description: '公司删除成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除公司失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新公司路由 - 返回布尔值
const updateCompanyRoute = createRoute({
  method: 'post',
  path: '/updateCompany',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: UpdateCompanySchema }
      }
    }
  },
  responses: {
    200: {
      description: '公司更新成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    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 getAllCompaniesRoute = createRoute({
  method: 'get',
  path: '/getAllCompanies',
  middleware: [authMiddleware],
  request: {
    query: PaginationQuerySchema
  },
  responses: {
    200: {
      description: '获取公司列表成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(CompanySchema).openapi({ description: '公司列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取公司列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 搜索公司路由 - 按名称模糊搜索
const searchCompaniesRoute = createRoute({
  method: 'get',
  path: '/searchCompanies',
  middleware: [authMiddleware],
  request: {
    query: SearchCompanyQuerySchema
  },
  responses: {
    200: {
      description: '搜索公司成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(CompanySchema).openapi({ description: '公司列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    400: {
      description: '搜索关键词不能为空',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '搜索公司失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 按平台获取公司路由
const getCompaniesByPlatformRoute = createRoute({
  method: 'get',
  path: '/getCompaniesByPlatform/{platformId}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      platformId: z.coerce.number().int().positive().openapi({
        param: { name: 'platformId', in: 'path' },
        example: 1,
        description: '平台ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取平台公司列表成功',
      content: {
        'application/json': {
          schema: z.array(CompanySchema).openapi({ description: '公司列表' })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取平台公司列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取单个公司路由
const getCompanyRoute = createRoute({
  method: 'get',
  path: '/getCompany/{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: CompanySchema.nullable() }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取公司详情失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 创建公司
  .openapi(createCompanyRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const companyService = new CompanyService(AppDataSource);

      const success = await companyService.createCompany(data);

      return c.json({ success }, 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建公司失败'
      }, 500);
    }
  })
  // 删除公司
  .openapi(deleteCompanyRoute, async (c) => {
    try {
      const { id } = c.req.valid('json');
      const companyService = new CompanyService(AppDataSource);

      const success = await companyService.deleteCompany(id);

      return c.json({ success }, 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(updateCompanyRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const companyService = new CompanyService(AppDataSource);

      const success = await companyService.updateCompany(data);
      return c.json({ success }, 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('公司不存在')) {
        return c.json({
          code: 404,
          message: '公司不存在'
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新公司失败'
      }, 500);
    }
  })
  // 获取所有公司
  .openapi(getAllCompaniesRoute, async (c) => {
    try {
      const { skip, take } = c.req.valid('query');
      const companyService = new CompanyService(AppDataSource);

      const result = await companyService.findAll(skip, take);

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取公司列表失败'
      }, 500);
    }
  })
  // 搜索公司
  .openapi(searchCompaniesRoute, async (c) => {
    try {
      const { name, skip, take } = c.req.valid('query');
      const companyService = new CompanyService(AppDataSource);

      const result = await companyService.searchByName(name, skip, take);

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '搜索公司失败'
      }, 500);
    }
  })
  // 按平台获取公司
  .openapi(getCompaniesByPlatformRoute, async (c) => {
    try {
      const { platformId } = c.req.valid('param');
      const companyService = new CompanyService(AppDataSource);

      const result = await companyService.findByPlatform(platformId);

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取平台公司列表失败'
      }, 500);
    }
  })
  // 获取单个公司
  .openapi(getCompanyRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const companyService = new CompanyService(AppDataSource);

      const result = await companyService.findOne(id);

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

      const validatedResult = await parseWithAwait(CompanySchema, result);
      return c.json(validatedResult, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取公司详情失败'
      }, 500);
    }
  });

export default app;