/**
 * API Service Layer for Redirect Intelligence v2
 * 
 * Centralized API interactions with type safety
 */

import axios, { AxiosInstance, AxiosResponse } from 'axios';

// Base configuration
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3333';

// Create axios instance
const api: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  withCredentials: true, // Include cookies for authentication
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor for auth token
api.interceptors.request.use(
  (config) => {
    // Auth token is handled via cookies, but we can add headers here if needed
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor for error handling
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // Unauthorized - redirect to login or handle session expiry
      console.log('Session expired or unauthorized');
    }
    return Promise.reject(error);
  }
);

// ============================================================================
// TYPE DEFINITIONS
// ============================================================================

export interface AuthUser {
  id: string;
  email: string;
  name: string;
  memberships: Array<{
    orgId: string;
    role: string;
    organization: {
      name: string;
      plan: string;
    };
  }>;
}

export interface LoginRequest {
  email: string;
  password: string;
}

export interface RegisterRequest {
  email: string;
  name: string;
  password: string;
  organizationName?: string;
}

export interface AuthResponse {
  success: boolean;
  data: {
    user: AuthUser;
    token?: string;
  };
  message?: string;
}

export interface HopResult {
  hopIndex: number;
  url: string;
  scheme?: string;
  statusCode?: number;
  redirectType: 'HTTP_301' | 'HTTP_302' | 'HTTP_307' | 'HTTP_308' | 'META_REFRESH' | 'JS' | 'FINAL' | 'OTHER';
  latencyMs?: number;
  contentType?: string;
  reason?: string;
  responseHeaders: Record<string, string>;
}

export interface CheckResult {
  id: string;
  inputUrl: string;
  method: string;
  status: 'OK' | 'ERROR' | 'TIMEOUT' | 'LOOP';
  finalUrl?: string;
  totalTimeMs: number;
  startedAt: string;
  finishedAt: string;
  hops: HopResult[];
  redirectCount: number;
  loopDetected?: boolean;
  error?: string;
}

export interface TrackRequestV2 {
  url: string;
  method?: 'GET' | 'POST' | 'HEAD';
  userAgent?: string;
  headers?: Record<string, string>;
  projectId?: string;
  followJS?: boolean;
  maxHops?: number;
  timeout?: number;
  enableSSLAnalysis?: boolean;
  enableSEOAnalysis?: boolean;
  enableSecurityAnalysis?: boolean;
}

export interface TrackResponseV2 {
  success: boolean;
  status: number;
  data: {
    check: CheckResult;
    url: string;
    method: string;
    redirectCount: number;
    finalUrl?: string;
    finalStatusCode?: number;
  };
  meta: {
    version: 'v2';
    enhanced: boolean;
    persisted: boolean;
    checkId: string;
  };
}

export interface SSLAnalysisResult {
  host: string;
  port: number;
  certificate?: {
    valid: boolean;
    subject: Record<string, string>;
    issuer: Record<string, string>;
    validFrom: string;
    validTo: string;
    daysToExpiry: number;
    keySize?: number;
    protocol?: string;
  };
  warnings: string[];
  errors: string[];
  securityScore: number;
  recommendations: string[];
}

export interface SEOAnalysisResult {
  url: string;
  flags: {
    robotsTxtStatus: string;
    hasTitle: boolean;
    hasDescription: boolean;
    titleLength?: number;
    descriptionLength?: number;
    noindex: boolean;
    nofollow: boolean;
    sitemapPresent: boolean;
    openGraphPresent: boolean;
    twitterCardPresent: boolean;
  };
  metaTags: {
    title?: string;
    description?: string;
    canonical?: string;
  };
  score: number;
  recommendations: string[];
  warnings: string[];
}

export interface SecurityAnalysisResult {
  url: string;
  flags: {
    safeBrowsingStatus: string;
    mixedContent: string;
    httpsToHttp: boolean;
    securityHeaders: {
      score: number;
    };
  };
  vulnerabilities: string[];
  recommendations: string[];
  securityScore: number;
}

// ============================================================================
// API SERVICES
// ============================================================================

export const authApi = {
  async login(credentials: LoginRequest): Promise<AuthResponse['data']> {
    const response: AxiosResponse<AuthResponse> = await api.post('/api/v1/auth/login', credentials);
    return response.data.data;
  },

  async register(userData: RegisterRequest): Promise<AuthResponse['data']> {
    const response: AxiosResponse<AuthResponse> = await api.post('/api/v1/auth/register', userData);
    return response.data.data;
  },

  async logout(): Promise<void> {
    await api.post('/api/v1/auth/logout');
  },

  async getCurrentUser(): Promise<AuthUser> {
    const response: AxiosResponse<AuthResponse> = await api.get('/api/v1/auth/me');
    return response.data.data.user;
  },

  async refreshToken(): Promise<string> {
    const response: AxiosResponse<{ data: { token: string } }> = await api.post('/api/v1/auth/refresh');
    return response.data.data.token;
  },
};

export const trackingApi = {
  async trackUrlV2(request: TrackRequestV2): Promise<TrackResponseV2['data']> {
    const response: AxiosResponse<TrackResponseV2> = await api.post('/api/v2/track', request);
    return response.data.data;
  },

  async getCheck(checkId: string): Promise<CheckResult> {
    const response: AxiosResponse<{ data: { check: CheckResult } }> = await api.get(`/api/v2/track/${checkId}`);
    return response.data.data.check;
  },

  async getProjectChecks(projectId: string, limit = 50, offset = 0): Promise<CheckResult[]> {
    const response: AxiosResponse<{ data: { checks: CheckResult[] } }> = await api.get(
      `/api/v2/projects/${projectId}/checks?limit=${limit}&offset=${offset}`
    );
    return response.data.data.checks;
  },

  async getRecentChecks(limit = 20): Promise<CheckResult[]> {
    const response: AxiosResponse<{ data: { checks: CheckResult[] } }> = await api.get(
      `/api/v2/checks/recent?limit=${limit}`
    );
    return response.data.data.checks;
  },

  // Legacy API for backward compatibility
  async trackUrlLegacy(url: string, method = 'GET', userAgent?: string): Promise<any> {
    const response = await api.post('/api/v1/track', { url, method, userAgent });
    return response.data;
  },
};

export const analysisApi = {
  async analyzeSSL(url: string): Promise<SSLAnalysisResult> {
    const response: AxiosResponse<{ data: { analysis: SSLAnalysisResult } }> = await api.post('/api/v2/analyze/ssl', { url });
    return response.data.data.analysis;
  },

  async analyzeSEO(url: string): Promise<SEOAnalysisResult> {
    const response: AxiosResponse<{ data: { analysis: SEOAnalysisResult } }> = await api.post('/api/v2/analyze/seo', { url });
    return response.data.data.analysis;
  },

  async analyzeSecurity(url: string): Promise<SecurityAnalysisResult> {
    const response: AxiosResponse<{ data: { analysis: SecurityAnalysisResult } }> = await api.post('/api/v2/analyze/security', { url });
    return response.data.data.analysis;
  },

  async analyzeComprehensive(url: string): Promise<{
    ssl: SSLAnalysisResult | null;
    seo: SEOAnalysisResult | null;
    security: SecurityAnalysisResult | null;
    summary: { overallScore: number; analysesCompleted: number; totalAnalyses: number };
  }> {
    const response: AxiosResponse<{ data: any }> = await api.post('/api/v2/analyze/comprehensive', { url });
    return response.data.data.analysis;
  },

  async getCheckAnalysis(checkId: string): Promise<{
    check: CheckResult;
    analysis: {
      ssl: any[];
      seo: any;
      security: any;
    };
  }> {
    const response: AxiosResponse<{ data: any }> = await api.get(`/api/v2/analyze/check/${checkId}`);
    return response.data.data;
  },
};

export const healthApi = {
  async getHealth(): Promise<{
    status: string;
    timestamp: string;
    version: string;
    environment: string;
  }> {
    const response: AxiosResponse<any> = await api.get('/health');
    return response.data;
  },
};

export default api;
