import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { OrderMtService } from '../../services';
import { ConfirmReceiptRequestDto, ConfirmReceiptResponseDto } from '../../schemas/confirm-receipt.schema';

const confirmReceiptRoute = createRoute({
  method: 'post',
  path: '/confirm-receipt',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: ConfirmReceiptRequestDto
        }
      }
    }
  },
  responses: {
    200: {
      description: '确认收货成功',
      content: {
        'application/json': {
          schema: ConfirmReceiptResponseDto
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '订单状态不允许确认收货',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器内部错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
})

const confirmReceiptRoutes = new OpenAPIHono<AuthContext>()
  // 确认收货路由
  .openapi( confirmReceiptRoute, async (c) => {
      const data = c.req.valid('json');
      const user = c.get('user');

      try {
        const orderService = new OrderMtService(AppDataSource);
        const result = await orderService.confirmReceipt(user.tenantId, data.orderId, user.id);

        return c.json({
          success: true,
          message: '确认收货成功',
          data: {
            orderId: result.orderId,
            state: result.state,
            updatedAt: result.updatedAt.toISOString(),
          }
        }, 200);
      } catch (error) {
        console.error('确认收货失败:', error);

        // 根据错误类型返回不同的状态码
        if (error instanceof Error) {
          if (error.message === '订单不存在') {
            return c.json(
              { code: 404, message: error.message },
              404
            );
          } else if (error.message === '只有已发货的订单才能确认收货') {
            return c.json(
              { code: 403, message: error.message },
              403
            );
          } else if (error.message === '只有已支付的订单才能确认收货') {
            return c.json(
              { code: 403, message: error.message },
              403
            );
          }
        }

        return c.json(
          { code: 500, message: error instanceof Error ? error.message : '确认收货失败' },
          500
        );
      }
    }
  );

export default confirmReceiptRoutes;