import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { SubscriptionRepository } from '../../infrastructure/repositories/subscription.repository';
import { SubscriptionLifecycleService } from '../../domain/services/subscription-lifecycle.service';

@Injectable()
export class CancelSubscriptionUseCase {
  private readonly logger = new Logger(CancelSubscriptionUseCase.name);

  constructor(
    private readonly subscriptionRepo: SubscriptionRepository,
    private readonly lifecycle: SubscriptionLifecycleService,
  ) {}

  /**
   * @param immediate true = cancel now, false = cancel at period end
   */
  async execute(tenantId: string, immediate = false): Promise<void> {
    const subscription = await this.subscriptionRepo.findByTenantId(tenantId);
    if (!subscription) throw new NotFoundException(`No subscription found for tenant ${tenantId}`);

    const updated = this.lifecycle.cancel(subscription, immediate);
    await this.subscriptionRepo.save(updated);

    if (immediate) {
      this.logger.log(`Tenant ${tenantId} subscription cancelled immediately`);
    } else {
      this.logger.log(`Tenant ${tenantId} subscription set to cancel at period end`);
    }
  }
}
