import { GenericCrudService } from '../../utils/generic-crud.service';
import { DataSource } from 'typeorm';
import { DeliveryAddress } from './delivery-address.entity';

export class DeliveryAddressService extends GenericCrudService<DeliveryAddress> {
  constructor(dataSource: DataSource) {
    super(dataSource, DeliveryAddress);
  }

  /**
   * 获取用户的收货地址列表
   * @param userId 用户ID
   * @returns 收货地址列表
   */
  async findByUser(userId: number): Promise<DeliveryAddress[]> {
    return this.repository.find({
      where: { userId, state: 1 },
      relations: ['user', 'province', 'city', 'district', 'town'],
      order: { isDefault: 'DESC', createdAt: 'DESC' }
    });
  }

  /**
   * 设置默认地址
   * @param id 地址ID
   * @param userId 用户ID
   * @returns 是否设置成功
   */
  async setDefault(id: number, userId: number): Promise<boolean> {
    await this.repository.manager.transaction(async (transactionalEntityManager) => {
      // 先将该用户的所有地址设为非默认
      await transactionalEntityManager.update(DeliveryAddress, 
        { userId }, 
        { isDefault: 0 }
      );
      
      // 将指定地址设为默认
      await transactionalEntityManager.update(DeliveryAddress,
        { id, userId },
        { isDefault: 1 }
      );
    });
    
    return true;
  }

  /**
   * 获取用户的默认地址
   * @param userId 用户ID
   * @returns 默认地址或null
   */
  async findDefaultByUser(userId: number): Promise<DeliveryAddress | null> {
    return this.repository.findOne({
      where: { userId, isDefault: 1, state: 1 },
      relations: ['user', 'province', 'city', 'district', 'town']
    });
  }
}