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 { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';
import { UserDeliveryAddressSchema } from '../schemas/user-delivery-address.schema';
import { parseWithAwait } from '@d8d/shared-utils';

// 设置默认地址路由
const setDefaultAddressRoute = createRoute({
  method: 'post',
  path: '/{id}/set-default',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '配送地址ID'
      })
    })
  },
  responses: {
    200: {
      description: '设置默认地址成功',
      content: {
        'application/json': { schema: UserDeliveryAddressSchema }
      }
    },
    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(setDefaultAddressRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const userId = c.get('user')?.id;

      if (!userId) {
        return c.json({
          code: 401,
          message: '用户未认证'
        }, 401);
      }

      const areaService = new AreaService(AppDataSource);
      const deliveryAddressService = new DeliveryAddressService(AppDataSource, areaService);

      // 使用服务层的设置默认地址方法
      const success = await deliveryAddressService.setDefault(id, userId);

      if (!success) {
        return c.json({
          code: 404,
          message: '配送地址不存在'
        }, 404);
      }

      // 获取更新后的地址信息
      const updatedAddress = await deliveryAddressService.findOne(id);
      if (!updatedAddress) {
        return c.json({
          code: 404,
          message: '配送地址不存在'
        }, 404);
      }

      return c.json(await parseWithAwait(UserDeliveryAddressSchema, updatedAddress), 200);
    } catch (error) {
      console.error('设置默认地址失败:', error);
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '设置默认地址失败'
      }, 500);
    }
  });

export default app;