import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';

/**
 * 租户状态
 */
export enum TenantStatus {
  ACTIVE = 'ACTIVE',
  SUSPENDED = 'SUSPENDED',
  ARCHIVED = 'ARCHIVED',
}

/**
 * 租户套餐
 */
export enum TenantPlan {
  FREE = 'FREE',
  STANDARD = 'STANDARD',
  ENTERPRISE = 'ENTERPRISE',
}

/**
 * 租户配置接口
 */
export interface TenantConfigData {
  branding?: {
    logoUrl?: string;
    primaryColor?: string;
    companyName?: string;
    favicon?: string;
  };
  ai?: {
    systemPrompt?: string;
    model?: string;
    temperature?: number;
    maxTokens?: number;
  };
  features?: {
    enableFileUpload?: boolean;
    enableKnowledgeBase?: boolean;
    enablePayments?: boolean;
    enableUserMemory?: boolean;
    enableAnalytics?: boolean;
  };
  notifications?: {
    webhookUrl?: string;
    emailNotifications?: boolean;
    smsNotifications?: boolean;
  };
}

/**
 * 租户 ORM 实体
 */
@Entity('tenants')
@Index('idx_tenants_slug', ['slug'], { unique: true })
@Index('idx_tenants_status', ['status'])
export class TenantORM {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', length: 100, unique: true })
  name: string;

  @Column({ type: 'varchar', length: 50, unique: true })
  slug: string;

  @Column({
    type: 'varchar',
    length: 20,
    default: TenantStatus.ACTIVE,
  })
  status: TenantStatus;

  @Column({
    type: 'varchar',
    length: 30,
    default: TenantPlan.STANDARD,
  })
  plan: TenantPlan;

  // 配额限制
  @Column({ name: 'max_users', type: 'int', default: 100 })
  maxUsers: number;

  @Column({ name: 'max_conversations_per_month', type: 'int', default: 10000 })
  maxConversationsPerMonth: number;

  @Column({ name: 'max_storage_mb', type: 'int', default: 5120 })
  maxStorageMb: number;

  // 当前使用量
  @Column({ name: 'current_user_count', type: 'int', default: 0 })
  currentUserCount: number;

  @Column({ name: 'current_conversation_count', type: 'int', default: 0 })
  currentConversationCount: number;

  @Column({ name: 'current_storage_bytes', type: 'bigint', default: 0 })
  currentStorageBytes: number;

  // 配置
  @Column({ type: 'jsonb', default: '{}' })
  config: TenantConfigData;

  // 账单信息
  @Column({ name: 'billing_email', type: 'varchar', length: 255, nullable: true })
  billingEmail: string | null;

  @Column({ name: 'billing_name', type: 'varchar', length: 100, nullable: true })
  billingName: string | null;

  @Column({ name: 'billing_phone', type: 'varchar', length: 20, nullable: true })
  billingPhone: string | null;

  // 时间戳
  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;

  @Column({ name: 'suspended_at', type: 'timestamptz', nullable: true })
  suspendedAt: Date | null;
}
