export class UrlParser {
  static getDomain(url: string): string {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname.replace(/^www\./, '');
    } catch (error) {
      throw new Error(`Invalid URL: ${url}`);
    }
  }

  static validateUrl(url: string): boolean {
    try {
      const urlObj = new URL(url);
      return urlObj.protocol === 'http:' || urlObj.protocol === 'https:';
    } catch {
      return false;
    }
  }

  static buildPageUrl(baseUrl: string, pageNum: number, config: any): string {
    try {
      const urlObj = new URL(baseUrl);
      if (config.pageParam) {
        urlObj.searchParams.set(config.pageParam, pageNum.toString());
      } else if (config.urlPattern) {
        // Replace {page} or similar patterns in URL
        return config.urlPattern.replace(/\{page\}/g, pageNum.toString());
      }
      return urlObj.toString();
    } catch (error) {
      throw new Error(`Failed to build page URL: ${error}`);
    }
  }

  static normalizeUrl(url: string, baseUrl?: string): string {
    try {
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      if (baseUrl) {
        return new URL(url, baseUrl).toString();
      }
      
      return url;
    } catch (error) {
      throw new Error(`Failed to normalize URL: ${url}`);
    }
  }

  static extractDomainConfig(url: string, sitesConfig: any): any {
    const domain = this.getDomain(url);
    const config = sitesConfig.sites[domain];
    
    if (!config) {
      throw new Error(`Unsupported site: ${domain}`);
    }
    
    return config;
  }
}