
import AuthService from '../services/AuthService';

const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'https://45.93.137.91.nip.io/api';
async function apiFetch(endpoint, options = {}) {
  const token = AuthService.getToken();
  const headers = {
    'Content-Type': 'application/json',
    ...(token && { Authorization: `Bearer ${token}` }),
    ...options.headers,
  };

  const response = await fetch(`${API_BASE}${endpoint}`, {
    ...options,
    headers,
  });

  if (!response.ok && response.status !== 206) {
    const errorText = await response.text().catch(() => '');
    throw new Error(`API Error ${response.status}: ${errorText}`);
  }

  const text = await response.text();
  if (!text) return null;

  try {
    const json = JSON.parse(text);
    return json && typeof json === 'object' && 'data' in json ? json.data : json;
  } catch {
    return text;
  }
}

/**
 * POST /Rating/AddPropertyRating
 * @param {Object} data - { reservationId, cleanRating, servicesRating, ownerBehaviorRating, experienceRating, comment? }
 */
export async function addPropertyRating(data) {
  return apiFetch('/Rating/AddPropertyRating', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/**
 * POST /Rating/AddCustomerRating
 * @param {Object} data - { reservationId, furnitureIntegrityRating, termsComplianceRating, renterBehaviorRating, comment? }
 */
export async function addCustomerRating(data) {
  return apiFetch('/Rating/AddCustomerRating', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

/**
 * GET /Rating/GetPropertyRatings
 * @param {number} propertyId
 * @param {number} page - default 1
 * @param {number} pageSize - default 10
 * @returns {Promise<{ items: Array, totalPages: number, currentPage: number }>}
 */
export async function getPropertyRatings(propertyId, page = 1, pageSize = 10) {
  const query = new URLSearchParams({
    propertyId: String(propertyId),
    page: String(page),
    pageSize: String(pageSize),
  }).toString();
  return apiFetch(`/Rating/GetPropertyRatings?${query}`);
}

/**
 * GET /Rating/GetCustomerRatings
 * @param {number} renterId
 * @param {number} page
 * @param {number} pageSize
 */
export async function getCustomerRatings(renterId, page = 1, pageSize = 10) {
  const query = new URLSearchParams({
    renterId: String(renterId),
    page: String(page),
    pageSize: String(pageSize),
  }).toString();
  return apiFetch(`/Rating/GetCustomerRatings?${query}`);
}

/**
 * GET /Rating/GetPropertyAverage
 * @param {number} propertyId
 * @returns {Promise<number>} average rating (0 if none)
 */
export async function getPropertyAverageRating(propertyId) {
  const result = await apiFetch(`/Rating/GetPropertyAverage?propertyId=${propertyId}`);
  if (typeof result === 'number') return result;
  if (result && typeof result.average === 'number') return result.average;
  return 0;
}