import api from './api';

interface ApiResponse<T> {
  success: boolean;
  data: T;
}

export interface Testimonial {
  id: string;
  agentProfileId: string;
  rating: number;
  text: string;
  authorName: string;
  authorRole: string;
  isPublished: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface GenerateLinkResponse {
  token: string;
}

export interface AgentByTokenResponse {
  id: string;
  firstName: string | null;
  lastName: string | null;
  avatar: string | null;
  agentType: { name: string } | null;
}

class TestimonialsService {
  private basePath = '/testimonials';

  async generateLink(): Promise<GenerateLinkResponse> {
    const response = await api.post<ApiResponse<GenerateLinkResponse>>(`${this.basePath}/generate-link`);
    return response.data.data;
  }

  async getMyTestimonials(sort: 'latest' | 'oldest' = 'latest'): Promise<Testimonial[]> {
    const response = await api.get<ApiResponse<Testimonial[]>>(`${this.basePath}/my?sort=${sort}`);
    return response.data.data;
  }

  async getAgentTestimonials(agentProfileId: string, limit?: number): Promise<Testimonial[]> {
    const params = limit ? `?limit=${limit}` : '';
    const response = await api.get<ApiResponse<Testimonial[]>>(`${this.basePath}/agent/${agentProfileId}${params}`);
    return response.data.data;
  }

  async getAgentByToken(token: string): Promise<AgentByTokenResponse> {
    const response = await api.get<ApiResponse<AgentByTokenResponse>>(`${this.basePath}/submit/${token}`);
    return response.data.data;
  }

  async submitTestimonial(token: string, data: { rating: number; text: string; authorName: string; authorRole: string }): Promise<Testimonial> {
    const response = await api.post<ApiResponse<Testimonial>>(`${this.basePath}/submit/${token}`, data);
    return response.data.data;
  }
}

export const testimonialsService = new TestimonialsService();
