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

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

  /**
   * 更新商户登录统计信息
   */
  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): Promise<Merchant | null> {
    return this.repository.findOne({
      where: { username }
    });
  }

  /**
   * 根据状态获取商户列表
   */
  async getByState(state: number): Promise<Merchant[]> {
    return this.repository.find({
      where: { state }
    });
  }
}