const $={maxWidth:1920,maxHeight:1920,quality:.8,maxSizeKo:500},f=["image/jpeg","image/png","image/webp"],z=a=>new Promise((c,l)=>{if(!f.includes(a.type)||a.size<=$.maxSizeKo*1024)return c(a);const m=new FileReader;m.onload=w=>{const i=new Image;i.onload=()=>{let{width:s,height:d}=i;const{maxWidth:h,maxHeight:o}=$;if(s>h||d>o){const e=Math.min(h/s,o/d);s=Math.round(s*e),d=Math.round(d*e)}const t=document.createElement("canvas");t.width=s,t.height=d,t.getContext("2d").drawImage(i,0,0,s,d);const r=a.type==="image/png"?"image/png":"image/jpeg";t.toBlob(e=>{if(!e)return l(new Error("Échec de la compression"));const g=new File([e],a.name,{type:r,lastModified:Date.now()}),p=((a.size-g.size)/a.size*100).toFixed(1);c(g)},r,$.quality)},i.onerror=()=>l(new Error("Impossible de charger l'image")),i.src=w.target.result},m.onerror=()=>l(new Error("Impossible de lire le fichier")),m.readAsDataURL(a)}),S=(a,c,l={})=>{const{defaultImage:m="",onError:w=o=>{}}=l,i=(o,t,n="image")=>`clients/${c.cloudId}/${c.id_societe}/${t}/${n}`,s=async(o,t,n="image")=>{const r=String(o).trim().replace(/[\r\n]/g,"");try{const e=await a.post(`${c.lienApi}/retourner_un_seulfichier`,null,{headers:{"x-path":`${i(r,t,n)}/${r}`}});if(e.data.length===0)return m;const g=n==="image"?`${i(r,t,n)}/${e.data[0]}`:`${i(r,t,n)}/${r}/${e.data[0]}`;return`${c.lienApi}/fichiers_public/${g}`}catch(e){if(e.response?.status===404)return m;throw e}};return{loadImage:s,uploadImage:(o,t,n="image")=>{const r=String(o).trim().replace(/[\r\n]/g,"");return new Promise((e,g)=>{const p=document.createElement("input");p.type="file",p.accept="image/*",p.onchange=async x=>{const I=x.target.files[0];if(!I)return g("No file selected");try{const u=await z(I),y=new FormData;y.append("file",u),await a.post(`${c.lienApi}/upload_un_fichier`,y,{headers:{"x-custom-filename":u.name,"x-path":`${i(r,t,n)}/${r}`}});const E=await s(o,t,n);e(E)}catch(u){g(u)}},p.click()})},deleteImage:async(o,t,n="image")=>{const r=String(o).trim().replace(/[\r\n]/g,"");try{return await a.post(`${c.lienApi}/deleteFile`,{},{headers:{"x-path":`${i(r,t,n)}/${r}`}}),m}catch(e){throw e}}}};export{z as a,S as c};
