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 baseUrl = `${API_BASE_URL}/api/policies`;

  /**
   * Get all policies
   */
  async getPolicies(): Promise<PolicyListItem[]> {
    try {
      const response = await fetch(`${this.baseUrl}/`, {
        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 response = await fetch(`${this.baseUrl}/${type}/`, {
        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;
    }
  }

  /**
   * Get a specific policy by ID
   */
  async getPolicyById(id: number): Promise<Policy> {
    try {
      const response = await fetch(`${this.baseUrl}/${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;


