import { API_URL, API_ORIGIN } from './config';
import type { DisposalPoint, Incident, User } from './types';

let token: string | null = null;
export function setToken(value: string | null) { token = value; }

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const headers: Record<string,string> = { ...(options.headers as Record<string,string> || {}) };
  if (token) headers.Authorization = `Bearer ${token}`;
  if (!(options.body instanceof FormData)) headers['Content-Type'] = 'application/json';
  const res = await fetch(`${API_URL}${path}`, { ...options, headers });
  const text = await res.text();
  const data = text ? JSON.parse(text) : null;
  if (!res.ok) throw new Error(data?.message || `Erro HTTP ${res.status}`);
  return data as T;
}

export const api = {
  register: (body: {name:string;email:string;password:string}) => request<{user:User;token:string}>('/auth/register',{method:'POST',body:JSON.stringify(body)}),
  login: (body: {email:string;password:string}) => request<{user:User;token:string}>('/auth/login',{method:'POST',body:JSON.stringify(body)}),
  me: () => request<{user:User}>('/me'),
  points: () => request<DisposalPoint[]>('/disposal-points'),
  incidents: () => request<Incident[]>('/incidents'),
  incident: (id:string) => request<Incident>(`/incidents/${id}`),
  stats: () => request<{totalIncidents:number;resolved:number;open:number;disposalPoints:number;categories:{category:string;count:number}[]}>('/stats'),
  confirm: (id:string) => request<Incident>(`/incidents/${id}/confirm`,{method:'POST'}),
  createIncident: async (data: {category:string;title:string;description:string;severity:string;latitude:number;longitude:number;imageUri?:string}) => {
    const form = new FormData();
    form.append('category', data.category); form.append('title', data.title); form.append('description', data.description);
    form.append('severity', data.severity); form.append('latitude', String(data.latitude)); form.append('longitude', String(data.longitude));
    if (data.imageUri) {
      const name = data.imageUri.split('/').pop() || 'evidence.jpg';
      const ext = name.split('.').pop() || 'jpg';
      form.append('image', { uri: data.imageUri, name, type: `image/${ext === 'jpg' ? 'jpeg' : ext}` } as any);
    }
    return request<Incident>('/incidents',{method:'POST',body:form});
  },
  imageUrl: (path?: string|null) => path ? (path.startsWith('http') ? path : `${API_ORIGIN}${path}`) : null
};
