import { Hono } from 'hono';
import { createCrudRoutes } from '@d8d/shared-crud';
import { GoodsMt } from '../entities/goods.entity.mt';
import { PublicGoodsSchema, PublicGoodsQueryDto } from '../schemas/public-goods.schema.mt';
import { FileMt } from '@d8d/file-module-mt';
import { GoodsServiceMt } from '../services/goods.service.mt';
import { AppDataSource } from '@d8d/shared-utils';

// 创建公开商品路由 - 只读查询，无需认证
// 默认只返回可用状态的商品

export const publicGoodsRoutesMt = createCrudRoutes({
  entity: GoodsMt,
  createSchema: undefined as any, // 禁用创建操作
  updateSchema: undefined as any, // 禁用更新操作
  getSchema: PublicGoodsSchema,
  listSchema: PublicGoodsSchema,
  searchFields: ['name', 'instructions'],
  relations: ['category1', 'category2', 'category3', 'supplier', 'merchant', 'imageFile.uploadUser', 'slideImages.uploadUser'],
  // 公开路由无需认证中间件
  middleware: [],
  // 公开路由不跟踪用户操作
  userTracking: undefined,
  relationFields: {
    slideImageIds: {
      relationName: 'slideImages',
      targetEntity: FileMt,
      joinTableName: 'goods_slide_images'
    }
  },
  // 公开路由不使用数据权限控制
  dataPermission: undefined,
  // 设置为只读模式
  readOnly: true,
  // 列表查询：只返回可用状态的父商品（spuId=0）
  listFilters: { state: 1, spuId: 0 },
  // 详情查询：只要求商品状态为可用，允许访问子商品
  detailFilters: { state: 1 },
  tenantOptions: {
    enabled: true,
    tenantIdField: 'tenantId'
  },
  // 使用自定义商品服务，支持父子商品详情
  serviceFactory: (dataSource, entity, options) => {
    return new GoodsServiceMt(dataSource);
  }
});