import { GenericCrudService } from '@d8d/shared-crud';
import { DataSource } from 'typeorm';
import { TenantEntityMt } from '../entities/tenant.entity';

export class TenantService extends GenericCrudService<TenantEntityMt> {
  constructor(dataSource: DataSource) {
    super(dataSource, TenantEntityMt, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      }
    });
  }

  /**
   * 根据租户代码查找租户
   */
  async findByCode(code: string): Promise<TenantEntityMt | null> {
    return this.repository.findOne({
      where: { code }
    });
  }

  /**
   * 根据状态获取租户列表
   */
  async getByStatus(status: number): Promise<TenantEntityMt[]> {
    return this.repository.find({
      where: { status }
    });
  }

  /**
   * 更新租户配置
   */
  async updateConfig(tenantId: number, config: Record<string, any>): Promise<boolean> {
    const tenant = await this.getById(tenantId);
    if (!tenant) {
      return false;
    }

    const updatedConfig = {
      ...tenant.config,
      ...config
    };

    await this.update(tenantId, { config: updatedConfig });
    return true;
  }
}