import { Injectable } from '@angular/core';
import { Product } from '../../../../core/products/models/product-domain.model';

export type ShareResult = 'native' | 'copied' | 'unsupported';

@Injectable({ providedIn: 'root' })
export class ProductShareService {
  async shareProduct(product: Product, productUrl: string): Promise<ShareResult> {
    if (typeof window === 'undefined') {
      return 'unsupported';
    }

    const title = product.name;
    const text = product.simpleDescription ?? product.name;

    if (typeof navigator !== 'undefined' && 'share' in navigator) {
      try {
        await navigator.share({ title, text, url: productUrl });
        return 'native';
      } catch {
        // User cancellation and unsupported payload should fall back to clipboard copy.
      }
    }

    if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(productUrl);
      return 'copied';
    }

    return 'unsupported';
  }
}
