import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { DeliveryAddressServiceMt } from '../services/delivery-address.mt.service';
import { AreaServiceMt } from '@d8d/geo-areas-mt';
import { AppDataSource, ErrorSchema } from '@d8d/shared-utils';
import { CreateUserDeliveryAddressDto, UpdateUserDeliveryAddressDto, UserDeliveryAddressSchema } from '../schemas/user-delivery-address.mt.schema';
import { parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';

// 创建配送地址路由 - 自定义业务逻辑（地区验证等）
const createDeliveryAddressRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateUserDeliveryAddressDto }
      }
    }
  },
  responses: {
    201: {
      description: '配送地址创建成功',
      content: {
        'application/json': { schema: UserDeliveryAddressSchema }
      }
    },
    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: UpdateUserDeliveryAddressDto }
      }
    }
  },
  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 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 user = c.get('user');
      const areaService = new AreaServiceMt(AppDataSource);
      const deliveryAddressService = new DeliveryAddressServiceMt(AppDataSource, areaService);

      // 自动设置当前用户ID
      const addressData = { ...data, userId: user.id };

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

      return c.json(await parseWithAwait(UserDeliveryAddressSchema, 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 user = c.get('user');
      const areaService = new AreaServiceMt(AppDataSource);
      const deliveryAddressService = new DeliveryAddressServiceMt(AppDataSource, areaService);

      console.debug('用户更新地址 - 用户ID:', user.id, '地址ID:', id);

      // 先检查地址是否存在且属于当前租户和用户
      const existingAddress = await deliveryAddressService.repository.findOne({
        where: {
          id,
          tenantId: user.tenantId
        }
      });
      console.debug('查询到的地址:', existingAddress);
      if (!existingAddress) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      // 检查数据权限 - 用户只能更新自己的地址
      if (existingAddress.userId !== user.id) {
        console.debug('权限检查失败: 地址用户ID', existingAddress.userId, '当前用户ID', user.id);
        return c.json({ code: 403, message: '权限不足，无法更新其他用户的地址' }, 403);
      }

      console.debug('权限检查通过，开始更新地址');

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

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

      return c.json(await parseWithAwait(UserDeliveryAddressSchema, result), 200);
    } catch (error) {
      console.error('用户更新地址错误:', 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 user = c.get('user');
      const areaService = new AreaServiceMt(AppDataSource);
      const deliveryAddressService = new DeliveryAddressServiceMt(AppDataSource, areaService);

      // 先检查地址是否存在且属于当前租户和用户
      const existingAddress = await deliveryAddressService.repository.findOne({
        where: {
          id,
          tenantId: user.tenantId
        }
      });
      if (!existingAddress) {
        return c.json({ code: 404, message: '资源不存在' }, 404);
      }

      // 检查数据权限 - 用户只能删除自己的地址
      if (existingAddress.userId !== user.id) {
        return c.json({ code: 403, message: '权限不足，无法删除其他用户的地址' }, 403);
      }

      // 使用通用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;