import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { MiniAuthService } from '../services/index.mt';
import { AppDataSource } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils';

// 获取快递公司列表请求Schema
const GetDeliveryCompaniesSchema = z.object({
  tenantId: z.number().optional()
});

// 快递公司信息Schema
const DeliveryCompanySchema = z.object({
  delivery_id: z.string(),
  delivery_name: z.string()
});

// 获取快递公司列表响应Schema
const GetDeliveryCompaniesResponseSchema = z.object({
  success: z.boolean(),
  message: z.string(),
  data: z.object({
    company_list: z.array(DeliveryCompanySchema)
  }).optional(),
  error: z.any().optional()
});

const getDeliveryCompaniesRoute = createRoute({
  method: 'post',
  path: '/get-delivery-companies',
  request: {
    body: {
      content: {
        'application/json': {
          schema: GetDeliveryCompaniesSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '获取快递公司列表成功',
      content: {
        'application/json': {
          schema: GetDeliveryCompaniesResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(getDeliveryCompaniesRoute, async (c) => {
  try {
    const miniAuthService = new MiniAuthService(AppDataSource);
    const { tenantId } = c.req.valid('json');

    // 调试输出
    const timestamp = new Date().toISOString();

    console.log('收到获取快递公司列表请求:', {
      tenantId,
      timestamp
    });

    // 调用服务获取快递公司列表
    const result = await miniAuthService.getCompanyList(tenantId);

    // 检查返回的数据结构
    if (!result.company_list || !Array.isArray(result.company_list)) {
      console.warn('微信API返回的快递公司列表格式不正确:', result);
      return c.json({
        code: 500,
        message: '快递公司列表格式不正确'
      }, 500);
    }

    return c.json({
      success: true,
      message: '获取快递公司列表成功',
      data: {
        company_list: result.company_list
      }
    }, 200);

  } catch (error) {
    console.error('获取快递公司列表失败:', error);

    const errorMessage = error instanceof Error ? error.message : '获取快递公司列表失败';
    const errorCode = (error as any)?.code || 500;

    return c.json({
      code: errorCode,
      message: errorMessage
    }, errorCode);
  }
});

export default app;