import { Capacitor, CapacitorHttp } from '@capacitor/core';
import { getToken, updateStoredClient } from './auth.js';

const API_BASE_KEY = 'eintervention_api_base';
const DEFAULT_API_BASE = (import.meta.env.VITE_API_BASE || 'http://192.168.1.103/Insuite_backbones/public').replace(/\/$/, '');

export function getApiBase() {
  return String(localStorage.getItem(API_BASE_KEY) || DEFAULT_API_BASE).trim().replace(/\/$/, '');
}

export function setApiBase(value) {
  const normalized = String(value || '').trim().replace(/\/$/, '');
  if (!normalized) {
    return '';
  }
  localStorage.setItem(API_BASE_KEY, normalized);
  return normalized;
}

function buildUrl(path) {
  if (path.startsWith('http')) {
    return path;
  }
  return getApiBase() + path;
}

function isNativePlatform() {
  if (typeof Capacitor?.isNativePlatform === 'function') {
    return Capacitor.isNativePlatform();
  }
  const platform = typeof Capacitor?.getPlatform === 'function' ? Capacitor.getPlatform() : 'web';
  return platform === 'android' || platform === 'ios';
}

function normalizeResponseData(data, headers) {
  const entries = Object.entries(headers || {});
  const contentType = String(entries.find(([key]) => key.toLowerCase() === 'content-type')?.[1] || '');
  if (typeof data === 'string' && contentType.includes('application/json')) {
    try {
      return JSON.parse(data);
    } catch {
      return null;
    }
  }
  return data;
}

async function request(method, path, body, extraHeaders = {}) {
  const headers = { ...extraHeaders };
  const token = getToken();
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  if (isNativePlatform() && !(body instanceof FormData)) {
    let payload = body;
    if (body instanceof URLSearchParams) {
      payload = body.toString();
    }
    const response = await CapacitorHttp.request({
      url: buildUrl(path),
      method,
      headers,
      data: payload,
    });
    const data = normalizeResponseData(response.data, response.headers);
    if (response.status < 200 || response.status >= 300) {
      const error = new Error('http_error');
      error.status = response.status;
      error.data = data;
      throw error;
    }
    return data;
  }

  const response = await fetch(buildUrl(path), {
    method,
    headers,
    body,
  });
  const contentType = response.headers.get('content-type') || '';
  const data = contentType.includes('application/json')
    ? await response.json().catch(() => null)
    : await response.text().catch(() => null);

  if (!response.ok) {
    const error = new Error('http_error');
    error.status = response.status;
    error.data = data;
    throw error;
  }

  return data;
}

export async function registerClient(payload) {
  const body = new URLSearchParams();
  Object.entries(payload || {}).forEach(([key, value]) => body.set(key, String(value ?? '')));
  return request('POST', '/api/public/mobile/register', body, {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  });
}

export async function loginClient(payload) {
  const body = new URLSearchParams();
  Object.entries(payload || {}).forEach(([key, value]) => body.set(key, String(value ?? '')));
  return request('POST', '/api/public/mobile/login', body, {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  });
}

export async function fetchProfile() {
  const data = await request('GET', '/api/public/mobile/me', undefined, { Accept: 'application/json' });
  if (data?.ok && data.client) {
    updateStoredClient(data.client);
  }
  return data;
}

export function createIncidentFormData(payload, files) {
  const formData = new FormData();
  Object.entries(payload || {}).forEach(([key, value]) => {
    formData.set(key, String(value ?? ''));
  });

  (files || []).forEach((item) => {
    if (!item?.file) {
      return;
    }
    formData.append('photos[]', item.file);
    formData.append('photo_comments[]', item.comment || '');
  });

  return formData;
}

export async function createIncident(formData) {
  return request('POST', '/api/public/mobile/incidents/create', formData, { Accept: 'application/json' });
}

export async function fetchIncidents() {
  return request('GET', '/api/public/mobile/incidents', undefined, { Accept: 'application/json' });
}

export async function fetchNotifications() {
  return request('GET', '/api/public/mobile/notifications', undefined, { Accept: 'application/json' });
}

export async function fetchUnreadCount() {
  return request('GET', '/api/public/mobile/notifications/unread-count', undefined, { Accept: 'application/json' });
}

export async function markNotificationsRead() {
  return request('POST', '/api/public/mobile/notifications/read-all', new URLSearchParams(), {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  });
}
