import type { PaymentOverview } from '../models/payment-overview.interface';
import type { SubscriptionProductInterface } from '../models/subscription-product.interface';
import { CandidateService } from '../services/candidate.service';
import { SubscriptionService } from '../services/subscription.service';

export interface SubscriptionSnapshot {
  paymentOverview: PaymentOverview | null;
  products: SubscriptionProductInterface | null;
}

export class SubscriptionPageViewModel {
  constructor(
    private readonly candidateService: CandidateService = new CandidateService(),
    private readonly subscriptionService: SubscriptionService = new SubscriptionService(),
  ) {}

  async getCandidateProfile(): Promise<{ imageUrl?: string; name: string }> {
    try {
      const candidate = await this.candidateService.getCandidate();
      return {
        name: candidate.firstName?.trim() || candidate.name?.trim() || 'Lasse',
        imageUrl: candidate.imageUrl || candidate.image || undefined,
      };
    } catch {
      return { name: 'Lasse' };
    }
  }

  async getSnapshot(): Promise<SubscriptionSnapshot> {
    const [paymentResult, productsResult] = await Promise.allSettled([
      this.subscriptionService.getPaymentOverview(),
      this.subscriptionService.getSubscriptionProducts(),
    ]);

    return {
      paymentOverview: paymentResult.status === 'fulfilled' ? paymentResult.value : null,
      products: productsResult.status === 'fulfilled' ? productsResult.value : null,
    };
  }

  async redeemCode(code: string): Promise<void> {
    await this.subscriptionService.redeemCode(code);
  }
}
