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

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

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

  async execute(tenantId: string, planName = 'free'): Promise<void> {
    // Check if subscription already exists
    const existing = await this.subscriptionRepo.findByTenantId(tenantId);
    if (existing) {
      this.logger.warn(`Subscription already exists for tenant ${tenantId}`);
      return;
    }

    const plan = await this.planRepo.findByName(planName);
    if (!plan) {
      throw new Error(`Plan '${planName}' not found`);
    }

    const subscription = this.lifecycle.createTrial(tenantId, plan);
    await this.subscriptionRepo.save(subscription);

    this.logger.log(`Created ${planName} trial subscription for tenant ${tenantId}`);
  }
}
