import { Result } from '../value-objects/Result';
import { ISubscriptionRepository } from '../repositories/ISubscriptionRepository';

export interface IStripeService {
  updateSubscription(subscriptionId: string, params: { cancel_at_period_end: boolean }): Promise<void>;
}

export class ReactivateSubscriptionUseCase {
  constructor(
    private subscriptionRepo: ISubscriptionRepository,
    private stripeService: IStripeService
  ) {}

  async execute(userId: string): Promise<Result<void>> {
    const subscriptions = await this.subscriptionRepo.findAllByUserId(userId);
    const subscription = subscriptions.find(sub => sub.willCancelAtPeriodEnd());
    if (!subscription) return Result.fail('No subscription scheduled for cancellation');

    const reactivateResult = subscription.reactivate();
    if (reactivateResult.isFailure()) return reactivateResult;

    return await this.updateSubscriptionInStripe(subscription);
  }

  private async updateSubscriptionInStripe(subscription: any): Promise<Result<void>> {
    try {
      await this.stripeService.updateSubscription(
        subscription.getStripeSubscriptionId(),
        { cancel_at_period_end: false }
      );
      await this.subscriptionRepo.save(subscription);
      return Result.ok(undefined);
    } catch (error) {
      return Result.fail(error instanceof Error ? error.message : 'Failed to reactivate subscription');
    }
  }
}
