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 { ChannelService } from '../services/channel.service';
import {
  CreateChannelSchema,
  UpdateChannelSchema,
  DeleteChannelSchema,
  ChannelSchema,
  PaginationQuerySchema,
  SearchChannelQuerySchema
} from '../schemas/channel.schema';

// 创建渠道路由 - 返回布尔值
const createChannelRoute = createRoute({
  method: 'post',
  path: '/createChannel',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateChannelSchema }
      }
    }
  },
  responses: {
    200: {
      description: '渠道创建成功',
      content: {
        'application/json': { schema: ChannelSchema }
      }
    },
    400: {
      description: '参数错误或渠道名称已存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建渠道失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除渠道路由 - 返回布尔值
const deleteChannelRoute = createRoute({
  method: 'post',
  path: '/deleteChannel',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: DeleteChannelSchema }
      }
    }
  },
  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 updateChannelRoute = createRoute({
  method: 'post',
  path: '/updateChannel',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: UpdateChannelSchema }
      }
    }
  },
  responses: {
    200: {
      description: '渠道更新成功',
      content: {
        'application/json': { schema: ChannelSchema }
      }
    },
    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 getAllChannelsRoute = createRoute({
  method: 'get',
  path: '/getAllChannels',
  middleware: [authMiddleware],
  request: {
    query: PaginationQuerySchema
  },
  responses: {
    200: {
      description: '获取渠道列表成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(ChannelSchema).openapi({ description: '渠道列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取渠道列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 搜索渠道路由 - 按名称模糊搜索
const searchChannelsRoute = createRoute({
  method: 'get',
  path: '/searchChannels',
  middleware: [authMiddleware],
  request: {
    query: SearchChannelQuerySchema
  },
  responses: {
    200: {
      description: '搜索渠道成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(ChannelSchema).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 getChannelRoute = createRoute({
  method: 'get',
  path: '/getChannel/{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: ChannelSchema.nullable() }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取渠道详情失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 创建渠道
  .openapi(createChannelRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const channelService = new ChannelService(AppDataSource);

      const result = await channelService.create(data);

      return c.json(await parseWithAwait(ChannelSchema, 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);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建渠道失败'
      }, 500);
    }
  })
  // 删除渠道
  .openapi(deleteChannelRoute, async (c) => {
    try {
      const { id } = c.req.valid('json');
      const channelService = new ChannelService(AppDataSource);

      const success = await channelService.delete(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(updateChannelRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const channelService = new ChannelService(AppDataSource);

      const result = await channelService.update(data.id, data);

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

      return c.json(await parseWithAwait(ChannelSchema, 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('渠道不存在')) {
        return c.json({
          code: 404,
          message: '渠道不存在'
        }, 404);
      }

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

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

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

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

      return c.json(result, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '搜索渠道失败'
      }, 500);
    }
  })
  // 获取单个渠道
  .openapi(getChannelRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const channelService = new ChannelService(AppDataSource);

      const result = await channelService.findOne(id);

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

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

export default app;