// src/services/testimonialService.ts

export interface Testimonial {
  id: number;
  name: string;
  age: number;
  title: string;
  story: string;
  outcome: string;
  impact: string;
  category: string;
  isActive: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

class TestimonialService {
  private baseUrl: string;

  constructor() {
    // Use environment variable or default to localhost
    this.baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
  }

  /**
   * Get all active testimonials (for public website)
   */
  async getActiveTestimonials(): Promise<Testimonial[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials/public`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        cache: 'no-store', // Always fetch fresh data
      });

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

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Error fetching active testimonials:', error);
      throw error;
    }
  }

  /**
   * Get all testimonials (for admin)
   */
  async getAllTestimonials(): Promise<Testimonial[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        cache: 'no-store',
      });

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

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Error fetching all testimonials:', error);
      throw error;
    }
  }

  /**
   * Get testimonial by ID
   */
  async getTestimonialById(id: number): Promise<Testimonial> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        cache: 'no-store',
      });

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

      const data = await response.json();
      return data;
    } catch (error) {
      console.error(`Error fetching testimonial ${id}:`, error);
      throw error;
    }
  }

  /**
   * Create new testimonial (admin only)
   */
  async createTestimonial(testimonial: Omit<Testimonial, 'id' | 'createdAt' | 'updatedAt'>): Promise<Testimonial> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(testimonial),
      });

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

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Error creating testimonial:', error);
      throw error;
    }
  }

  /**
   * Update testimonial (admin only)
   */
  async updateTestimonial(id: number, testimonial: Omit<Testimonial, 'id' | 'createdAt' | 'updatedAt'>): Promise<Testimonial> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(testimonial),
      });

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

      const data = await response.json();
      return data;
    } catch (error) {
      console.error(`Error updating testimonial ${id}:`, error);
      throw error;
    }
  }

  /**
   * Delete testimonial (admin only)
   */
  async deleteTestimonial(id: number): Promise<void> {
    try {
      const response = await fetch(`${this.baseUrl}/api/testimonials/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error(`Error deleting testimonial ${id}:`, error);
      throw error;
    }
  }
}

// Export singleton instance
const testimonialService = new TestimonialService();
export default testimonialService;