import { UrlCheckResult, UrlVerdict, ThreatInfo, PhishingReport, SubscriptionTier } from '../types';
import { settingsManager } from './settings';
import { API_TIMEOUT } from './cache';

export class ShieldApiClient {
  private baseUrl: string = '';

  async checkUrl(url: string): Promise<UrlCheckResult | null> {
    const settings = await settingsManager.get();
    const token = settings.authToken;
    if (!token) return null;

    const startTime = Date.now();
    try {
      const response = await fetch(`${settings.apiBaseUrl}/extension/url-check`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ url }),
        signal: AbortSignal.timeout(API_TIMEOUT),
      });

      if (!response.ok) return null;

      const data = await response.json();
      const latency = Date.now() - startTime;

      return {
        url,
        domain: new URL(url).hostname,
        verdict: data.verdict || UrlVerdict.UNKNOWN,
        confidence: data.confidence || 0,
        threats: (data.threats || []) as ThreatInfo[],
        cached: false,
        latencyMs: latency,
        timestamp: Date.now(),
      };
    } catch {
      return null;
    }
  }

  async checkDomainExposure(domain: string): Promise<{ exposed: boolean; sources: string[] } | null> {
    const settings = await settingsManager.get();
    const token = settings.authToken;
    if (!token || !settings.darkWatchEnabled) return null;

    try {
      const response = await fetch(`${settings.apiBaseUrl}/darkwatch/exposures/check`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify({ domain }),
        signal: AbortSignal.timeout(API_TIMEOUT),
      });

      if (!response.ok) return null;
      return response.json();
    } catch {
      return null;
    }
  }

  async submitPhishingReport(report: PhishingReport): Promise<boolean> {
    const settings = await settingsManager.get();
    const token = settings.authToken;
    if (!token) return false;

    try {
      const response = await fetch(`${settings.apiBaseUrl}/extension/phishing-report`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(report),
        signal: AbortSignal.timeout(3000),
      });
      return response.ok;
    } catch {
      return false;
    }
  }

  async authenticate(apiKey: string): Promise<{ userId: string; tier: SubscriptionTier } | null> {
    try {
      const settings = await settingsManager.get();
      const response = await fetch(`${settings.apiBaseUrl}/extension/auth`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`,
        },
        signal: AbortSignal.timeout(5000),
      });

      if (!response.ok) return null;
      return response.json();
    } catch {
      return null;
    }
  }

  async getProtectionStats(): Promise<{
    threatsBlockedToday: number;
    urlsCheckedToday: number;
  } | null> {
    const settings = await settingsManager.get();
    const token = settings.authToken;
    if (!token) return null;

    try {
      const response = await fetch(`${settings.apiBaseUrl}/extension/stats`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        signal: AbortSignal.timeout(3000),
      });

      if (!response.ok) return null;
      return response.json();
    } catch {
      return null;
    }
  }
}

export const shieldApiClient = new ShieldApiClient();
