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 CancelSubscriptionUseCase {
  constructor(
    private subscriptionRepo: ISubscriptionRepository,
    private stripeService: IStripeService
  ) {}

  async execute(userId: string): Promise<Result<void>> {
    const subscription = await this.subscriptionRepo.findActiveByUserId(userId);
    if (!subscription) return Result.fail('No active subscription found');

    const scheduleResult = subscription.scheduleForCancellation();
    if (scheduleResult.isFailure()) return scheduleResult;

    return await this.updateSubscriptionInStripe(subscription);
  }

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