import { API_BASE_URL } from '../config/api';

export interface PolicySection {
  id: number;
  heading: string;
  content: string;
  order: number;
}

export interface Policy {
  id: number;
  type: 'privacy' | 'terms' | 'support';
  title: string;
  slug: string;
  description: string;
  last_updated: string;
  version: string;
  effective_date: string;
  sections: PolicySection[];
}

export interface PolicyListItem {
  id: number;
  type: 'privacy' | 'terms' | 'support';
  title: string;
  slug: string;
  description: string;
  last_updated: string;
  version: string;
}

class PolicyServiceAPI {
  private getBaseUrl(): string {
    // Safely get base URL, handling both server and client environments
    try {
      const base = API_BASE_URL || '';
      if (base) {
        return `${base}/api/policies`;
      }
      // Fallback for SSR or when API_BASE_URL is not available
      if (typeof window !== 'undefined') {
        // Client-side: use relative URL (proxied by nginx)
        return '/api/policies';
      }
      // Server-side: use environment variable or fallback
      return `${process.env.NEXT_PUBLIC_SITE_URL || 'https://gnxsoft.com'}/api/policies`;
    } catch (error) {
      // Ultimate fallback
      if (typeof window !== 'undefined') {
        return '/api/policies';
      }
      return 'https://gnxsoft.com/api/policies';
    }
  }

  /**
   * Get all policies
   */
  async getPolicies(): Promise<PolicyListItem[]> {
    try {
      const response = await fetch(`${this.getBaseUrl()}/`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.results || data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * Get a specific policy by type
   */
  async getPolicyByType(type: 'privacy' | 'terms' | 'support'): Promise<Policy> {
    try {
      const baseUrl = this.getBaseUrl();
      const url = `${baseUrl}/${type}/`;
      
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        // Add cache control for client-side requests
        cache: 'no-store',
      });

      if (!response.ok) {
        const errorText = await response.text().catch(() => 'Unknown error');
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const data = await response.json();
      
      // Validate response structure
      if (!data || typeof data !== 'object') {
        throw new Error('Invalid response format from API');
      }
      
      return data;
    } catch (error) {
      // Log error for debugging (only on client side)
      if (typeof window !== 'undefined') {
        console.error(`Error fetching policy type "${type}":`, error);
      }
      throw error;
    }
  }

  /**
   * Get a specific policy by ID
   */
  async getPolicyById(id: number): Promise<Policy> {
    try {
      const response = await fetch(`${this.getBaseUrl()}/${id}/`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      throw error;
    }
  }
}

// Export a singleton instance
export const policyService = new PolicyServiceAPI();

// Export individual functions for convenience
export const getPolicies = () => policyService.getPolicies();
export const getPolicyByType = (type: 'privacy' | 'terms' | 'support') => policyService.getPolicyByType(type);
export const getPolicyById = (id: number) => policyService.getPolicyById(id);

export default policyService;


