import { API_BASE_URL } from './config';
import { getSession, saveSession, type MobileSession } from './session';

async function json<T>(path:string,options:RequestInit={},token?:string):Promise<T>{
 const headers=new Headers(options.headers);if(!(options.body instanceof FormData))headers.set('Content-Type','application/json');if(token)headers.set('Authorization',`Bearer ${token}`);headers.set('X-Device-Name','COLORJET Engineer Android');
 const r=await fetch(`${API_BASE_URL}${path}`,{...options,headers});const body=await r.json().catch(()=>null);if(!r.ok||!body?.ok)throw new Error(body?.error?.message||`Request failed (${r.status})`);return body.data as T;
}
export async function authed<T>(path:string,options:RequestInit={}):Promise<T>{const s=await getSession();if(!s)throw new Error('Please sign in again.');try{return await json<T>(path,options,s.accessToken);}catch(error){if(error instanceof Error&&error.message.includes('expired')){const refreshed=await refresh(s);return json<T>(path,options,refreshed.accessToken);}throw error;}}
export async function refresh(s:MobileSession):Promise<MobileSession>{const next=await json<MobileSession>('/auth/refresh',{method:'POST',body:JSON.stringify({refreshToken:s.refreshToken,deviceName:'COLORJET Engineer Android'})});await saveSession(next);return next;}
export const api={
 login:(identifier:string,password:string)=>json<MobileSession>('/auth/login',{method:'POST',body:JSON.stringify({identifier,password,deviceName:'COLORJET Engineer Android'})}),
 me:()=>authed<any>('/auth/me'),
 tickets:()=>authed<any[]>('/service-tickets'),
 ticket:(id:string)=>authed<any>(`/service-tickets/${id}`),
 start:(id:string,payload:any)=>authed<any>(`/service-tickets/${id}/start`,{method:'POST',body:JSON.stringify(payload)}),
 complete:(id:string,payload:any)=>authed<any>(`/service-tickets/${id}/complete`,{method:'POST',body:JSON.stringify(payload)}),
 note:(id:string,note:string)=>authed<any>(`/service-tickets/${id}/note`,{method:'POST',body:JSON.stringify({note})}),
 engineers:()=>authed<any[]>('/engineers'),
 schedule:(id:string)=>authed<any[]>(`/engineers/${id}/schedule`),
 products:(q='')=>authed<any[]>(`/stock/products?q=${encodeURIComponent(q)}`),
 registerPushDevice:(payload:{token:string;platform:string;deviceName?:string;deviceModel?:string;appVersion?:string})=>authed<any>('/notifications/devices',{method:'POST',body:JSON.stringify(payload)}),
 unregisterPushDevice:(token:string)=>authed<any>('/notifications/devices',{method:'DELETE',body:JSON.stringify({token})}),
 upload:async(ticketId:string,uri:string,fileType:string)=>{const s=await getSession();if(!s)throw new Error('Please sign in again.');const form=new FormData();form.append('ticketId',ticketId);form.append('fileType',fileType);form.append('file',{uri,name:`service-${Date.now()}.jpg`,type:'image/jpeg'} as any);const r=await fetch(`${API_BASE_URL}/files`,{method:'POST',headers:{Authorization:`Bearer ${s.accessToken}`},body:form});const body=await r.json().catch(()=>null);if(!r.ok||!body?.ok)throw new Error(body?.error?.message||'Photo upload failed.');return body.data;}
};
