import api from '@/lib/api';
import type { ApiReview, ApiReviewsResponse } from '@/types/api';

export interface CreateReviewPayload {
  product_id: number;
  rating: number;
  comment: string;
}

export interface UpdateReviewPayload {
  rating?: number;
  comment?: string;
}

export interface CanReviewResponse {
  can_review: boolean;
  reason?: string;
  has_purchased?: boolean;
  message?: string;
  existing_review?: ApiReview;
}

// Review API Service
export const reviewApi = {
  // Get reviews for a product
  async getReviews(
    productId: number,
    params?: {
      page?: number;
      per_page?: number;
      sort_by?: 'recent' | 'rating_high' | 'rating_low' | 'verified';
    }
  ): Promise<ApiReviewsResponse> {
    const queryParams = new URLSearchParams();
    
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.per_page) queryParams.append('per_page', params.per_page.toString());
    if (params?.sort_by) queryParams.append('sort_by', params.sort_by);
    
    const query = queryParams.toString();
    const endpoint = query 
      ? `/products/${productId}/reviews?${query}` 
      : `/products/${productId}/reviews`;
    
    return api.get<ApiReviewsResponse>(endpoint);
  },

  // Check if user can review a product
  async canReview(productId: number): Promise<CanReviewResponse> {
    return api.get<CanReviewResponse>(`/products/${productId}/reviews/can-review`);
  },

  // Create a new review (requires authentication)
  async createReview(payload: CreateReviewPayload): Promise<{ message: string; data: ApiReview }> {
    return api.post<{ message: string; data: ApiReview }>(
      `/products/${payload.product_id}/reviews`,
      payload
    );
  },

  // Update a review (requires authentication and ownership)
  async updateReview(reviewId: number, payload: UpdateReviewPayload): Promise<{ message: string; data: ApiReview }> {
    return api.put<{ message: string; data: ApiReview }>(
      `/reviews/${reviewId}`,
      payload
    );
  },

  // Delete a review (requires authentication and ownership)
  async deleteReview(reviewId: number): Promise<{ message: string }> {
    return api.delete<{ message: string }>(`/reviews/${reviewId}`);
  },
};

export default reviewApi;
