import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { DeliveryAddressService } from '../services/delivery-address.service';
import { AreaService } from '@d8d/geo-areas';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { CreateAdminDeliveryAddressDto, UpdateAdminDeliveryAddressDto, AdminDeliveryAddressSchema } from '../schemas/admin-delivery-address.schema';
import { parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';

// 创建配送地址路由 - 自定义业务逻辑（地区验证等）
const createDeliveryAddressRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateAdminDeliveryAddressDto }
      }
    }
  },
  responses: {
    201: {
      description: '配送地址创建成功',
      content: {
        'application/json': { schema: AdminDeliveryAddressSchema }
      }
    },
    400: {
      description: '参数错误或地区数据验证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建配送地址失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新配送地址路由 - 自定义业务逻辑（地区验证等）
const updateDeliveryAddressRoute = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '配送地址ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: UpdateAdminDeliveryAddressDto }
      }
    }
  },
  responses: {
    200: {
      description: '配送地址更新成功',
      content: {
        'application/json': { schema: AdminDeliveryAddressSchema }
      }
    },
    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 deleteDeliveryAddressRoute = createRoute({
  method: 'delete',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '配送地址ID'
      })
    })
  },
  responses: {
    204: { description: '配送地址删除成功' },
    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(createDeliveryAddressRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const areaService = new AreaService(AppDataSource);
      const deliveryAddressService = new DeliveryAddressService(AppDataSource, areaService);

      // 使用包含地区验证的创建方法
      const result = await deliveryAddressService.createWithValidation(data);

      return c.json(await parseWithAwait(AdminDeliveryAddressSchema, result), 201);
    } 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: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建配送地址失败'
      }, 500);
    }
  })
  .openapi(updateDeliveryAddressRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const data = c.req.valid('json');
      const areaService = new AreaService(AppDataSource);
      const deliveryAddressService = new DeliveryAddressService(AppDataSource, areaService);

      // 使用包含地区验证的更新方法
      const result = await deliveryAddressService.updateWithValidation(id, data);

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

      return c.json(await parseWithAwait(AdminDeliveryAddressSchema, 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: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新配送地址失败'
      }, 500);
    }
  })
  .openapi(deleteDeliveryAddressRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const areaService = new AreaService(AppDataSource);
      const deliveryAddressService = new DeliveryAddressService(AppDataSource, areaService);

      // 使用通用CRUD服务的删除方法
      const success = await deliveryAddressService.delete(id);

      if (!success) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      return c.body(null, 204);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除配送地址失败'
      }, 500);
    }
  });

export default app;