import { createParamDecorator, ExecutionContext, SetMetadata } from '@nestjs/common';
import { TenantContext, TenantRequest } from './tenant.types.js';

/**
 * 获取当前租户 ID
 * @example
 * @Get()
 * async findAll(@TenantId() tenantId: string) { ... }
 */
export const TenantId = createParamDecorator(
  (_data: unknown, ctx: ExecutionContext): string => {
    const request = ctx.switchToHttp().getRequest<TenantRequest>();
    return request.tenantId;
  },
);

/**
 * 获取完整的租户上下文
 * @example
 * @Get()
 * async findAll(@Tenant() tenant: TenantContext) { ... }
 */
export const Tenant = createParamDecorator(
  (_data: unknown, ctx: ExecutionContext): TenantContext => {
    const request = ctx.switchToHttp().getRequest<TenantRequest>();
    return request.tenant;
  },
);

/**
 * 元数据键：需要的功能特性
 */
export const REQUIRED_FEATURES_KEY = 'requiredFeatures';

/**
 * 标记端点需要特定功能特性
 * @example
 * @RequireFeatures('enableFileUpload', 'enablePayments')
 * @Post('upload')
 * async upload() { ... }
 */
export const RequireFeatures = (...features: string[]) =>
  SetMetadata(REQUIRED_FEATURES_KEY, features);

/**
 * 元数据键：需要的租户套餐
 */
export const REQUIRED_PLANS_KEY = 'requiredPlans';

/**
 * 标记端点需要特定套餐
 * @example
 * @RequirePlans('STANDARD', 'ENTERPRISE')
 * @Get('premium-feature')
 * async premiumFeature() { ... }
 */
export const RequirePlans = (...plans: string[]) =>
  SetMetadata(REQUIRED_PLANS_KEY, plans);

/**
 * 元数据键：跳过租户检查
 */
export const SKIP_TENANT_CHECK_KEY = 'skipTenantCheck';

/**
 * 标记端点跳过租户检查 (用于公共端点)
 * @example
 * @SkipTenantCheck()
 * @Get('health')
 * async health() { ... }
 */
export const SkipTenantCheck = () => SetMetadata(SKIP_TENANT_CHECK_KEY, true);
