import { CapacitorHttp, type HttpOptions } from '@capacitor/core' import type { ForecastAllResponse, ForecastStationResponse, StationsResponse, TokenResponse, UserResponse, } from '../types' const API_PREFIX = '/api/v1' const RAW_DEFAULT_BASE_URL = import.meta.env.VITE_API_BASE_URL?.trim() export class ApiError extends Error { status: number constructor(status: number, detail: string) { super(detail) this.name = 'ApiError' this.status = status } } function parseErrorDetail(payload: unknown): string { if (typeof payload === 'string' && payload.trim()) { return payload } if (payload && typeof payload === 'object' && 'detail' in payload) { const detail = Reflect.get(payload, 'detail') if (typeof detail === 'string' && detail.trim()) { return detail } } return 'No se pudo completar la petición.' } export function normalizeBaseUrl(rawUrl: string): string { return rawUrl.trim().replace(/\/+$/, '').replace(/\/api\/v1$/, '') } export function getDefaultApiBaseUrl(): string { return normalizeBaseUrl(RAW_DEFAULT_BASE_URL || 'http://10.0.2.2:8000') } function buildApiUrl(baseUrl: string, path: string): string { const normalized = normalizeBaseUrl(baseUrl) if (!normalized) { throw new ApiError(0, 'Configura la URL del backend antes de iniciar sesión.') } return `${normalized}${API_PREFIX}${path}` } async function request( baseUrl: string, path: string, init: { method?: HttpOptions['method'] token?: string headers?: Record data?: unknown } = {}, ): Promise { const { method = 'GET', token, headers = {}, data } = init const response = await CapacitorHttp.request({ url: buildApiUrl(baseUrl, path), method, headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers, }, data, }) if (response.status >= 400) { throw new ApiError(response.status, parseErrorDetail(response.data)) } return response.data as T } export function getHealth(baseUrl: string) { return request<{ status: string; timestamp: string }>(baseUrl, '/health') } export function registerUser(baseUrl: string, email: string, password: string) { return request(baseUrl, '/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json', }, data: { email, password }, }) } export function loginUser(baseUrl: string, email: string, password: string) { return request(baseUrl, '/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, data: new URLSearchParams({ username: email, password, }).toString(), }) } export function fetchStations(baseUrl: string, token: string) { return request(baseUrl, '/stations', { token }) } export function fetchForecastAll(baseUrl: string, token: string) { return request(baseUrl, '/forecast', { token }) } export function fetchForecastStation( baseUrl: string, token: string, stationId: string, ) { return request(baseUrl, `/forecast/${stationId}`, { token, }) }