import { GenericCrudService } from '@d8d/shared-crud';
import { DataSource } from 'typeorm';
import { MerchantMt } from '../entities/merchant.mt.entity';

export class MerchantServiceMt extends GenericCrudService<MerchantMt> {
  constructor(dataSource: DataSource) {
    super(dataSource, MerchantMt, {
      userTracking: {
        createdByField: 'createdBy',
        updatedByField: 'updatedBy'
      },
      tenantOptions: {
        tenantIdField: 'tenantId'
      }
    });
  }

  /**
   * 更新商户登录统计信息
   */
  async updateLoginStats(
    merchantId: number,
    loginTime: number,
    loginIp: string
  ): Promise<boolean> {
    const merchant = await this.getById(merchantId);
    if (!merchant) {
      return false;
    }

    // 更新登录统计
    const updateData = {
      loginNum: merchant.loginNum + 1,
      lastLoginTime: merchant.loginTime,
      lastLoginIp: merchant.loginIp,
      loginTime,
      loginIp
    };

    await this.update(merchantId, updateData);
    return true;
  }

  /**
   * 根据用户名查找商户（包含租户过滤）
   */
  async findByUsername(username: string, tenantId?: number): Promise<MerchantMt | null> {
    const where: any = { username };
    if (tenantId !== undefined) {
      where.tenantId = tenantId;
    }
    return this.repository.findOne({
      where
    });
  }

  /**
   * 根据状态获取商户列表（包含租户过滤）
   */
  async getByState(state: number, tenantId?: number): Promise<MerchantMt[]> {
    const where: any = { state };
    if (tenantId !== undefined) {
      where.tenantId = tenantId;
    }
    return this.repository.find({
      where
    });
  }
}