import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { ServerDirectoryFacade } from '../../../server-directory';
import { LinkMetadata } from '../../../../shared-kernel';

const URL_PATTERN = /https?:\/\/[^\s<>)"']+/g;

@Injectable({ providedIn: 'root' })
export class LinkMetadataService {
  private readonly http = inject(HttpClient);
  private readonly serverDirectory = inject(ServerDirectoryFacade);

  extractUrls(content: string): string[] {
    return [...content.matchAll(URL_PATTERN)].map((match) => match[0]);
  }

  async fetchMetadata(url: string): Promise<LinkMetadata> {
    try {
      const apiBase = this.serverDirectory.getApiBaseUrl();
      const result = await firstValueFrom(
        this.http.get<Omit<LinkMetadata, 'url'>>(
          `${apiBase}/link-metadata`,
          { params: { url } }
        )
      );

      return { url, ...result };
    } catch {
      return { url, failed: true };
    }
  }

  async fetchAllMetadata(urls: string[]): Promise<LinkMetadata[]> {
    const unique = [...new Set(urls)];

    return Promise.all(unique.map((url) => this.fetchMetadata(url)));
  }
}
