import db from '../../config/database';
import { logger } from '../../utils/logger';

export interface Tenant {
  id: string;
  name: string;
  type: 'SaaS' | 'Enterprise' | 'Individual';
  status: 'active' | 'suspended' | 'canceled';
  createdAt: number;
}

export interface Organization {
  id: string;
  tenantId: string;
  parentId?: string; // 支持组织树
  name: string;
  createdAt: number;
}

export interface Shop {
  id: string;
  tenantId: string;
  orgId: string;
  platform: string;
  name: string;
  status: 'active' | 'inactive';
  createdAt: number;
}

export interface UserContext {
  userId: string;
  tenantId: string;
  orgId: string;
  shopIds: string[]; // 用户可访问的店铺列表
  roleCode: string;
  permissions: string[];
}

/**
 * [CORE_TOB_01] TOB 租户主数据模型 (Tenant Master Data)
 * @description 建立 tenant -> organization -> shop -> user 关系与隔离逻辑
 */
export class TenantService {
  /**
   * 初始化数据库表
   */
  static async initTable() {
    // 1. Tenants 表
    const hasTenantsTable = await db.schema.hasTable('cf_tenants');
    if (!hasTenantsTable) {
      console.log('📦 Creating cf_tenants table...');
      await db.schema.createTable('cf_tenants', (table) => {
        table.string('id', 64).primary();
        table.string('name', 128).notNullable();
        table.string('code', 64).unique().notNullable();
        table.string('status', 16).defaultTo('active');
        table.string('owner_id', 64);
        table.json('config');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
      console.log('✅ Table cf_tenants created');
    }

    // 2. Organization 表
    const hasOrgTable = await db.schema.hasTable('cf_organization');
    if (!hasOrgTable) {
      console.log('📦 Creating cf_organization table...');
      await db.schema.createTable('cf_organization', (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('parent_id', 64);
        table.string('name', 128).notNullable();
        table.string('level', 16);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id']);
      });
      console.log('✅ Table cf_organization created');
    }

    // 3. Shop 表
    const hasShopTable = await db.schema.hasTable('cf_shop');
    if (!hasShopTable) {
      console.log('📦 Creating cf_shop table...');
      await db.schema.createTable('cf_shop', (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('org_id', 64);
        table.string('platform', 32).notNullable();
        table.string('name', 128).notNullable();
        table.string('external_shop_id', 128);
        table.string('status', 16).defaultTo('active');
        table.json('credentials');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id']);
      });
      console.log('✅ Table cf_shop created');
    }
  }

  /**
   * 获取用户的租户上下文
   */
  static async getUserContext(userId: string): Promise<UserContext> {
    logger.info(`[Tenant] Fetching context for user: ${userId}`);
    // 实际业务中应从 cf_users, cf_tenant_members, cf_shop_access 等表查询
    // Mock 返回
    return {
      userId,
      tenantId: 'TEN-123',
      orgId: 'ORG-456',
      shopIds: ['SHOP-789', 'SHOP-000'],
      roleCode: 'ADMIN',
      permissions: ['publish:execute', 'risk:approve', 'billing:view']
    };
  }

  /**
   * 租户数据隔离逻辑：在查询时强制注入 tenantId 过滤
   */
  static applyDataScope(query: any, context: UserContext): any {
    logger.info(`[Tenant] Applying data scope for Tenant: ${context.tenantId}`);
    return query.where('tenant_id', context.tenantId);
  }

  /**
   * 接口级权限校验
   */
  static hasPermission(context: UserContext, permission: string): boolean {
    if (context.roleCode === 'ADMIN') return true;
    return context.permissions.includes(permission);
  }
}
