const calculateSovereignSplit = (totalAmount,env) =>{const empireRatio = parseFloat(env.EMPIRE_PART || "0.85");return{systemDebit:Math.floor(totalAmount * empireRatio),yarmotekPure: Math.floor(totalAmount * .8),techSecurity: Math.floor(totalAmount * .02),agentInHand: Math.floor(totalAmount * (1 - empireRatio))}}; export default{async fetch(request,env,ctx){const url = new url(request.url);const pathname = url.pathname;const corsHeaders ={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "GET, POST, PUT, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",}if (request.method === "OPTIONS") return new Response(null,{headers: corsHeaders});try{if (pathname === "/api/agent/status" && request.method === "GET"){const id = url.searchParams.get("id");if (!id) return new Response(JSON.stringify({error: "MISSING_ID"}),{status: 400,headers: corsHeaders});const agent = await env.DB.prepare("SELECT balance, grade FROM resellers_pro WHERE agent_id = ?").bind(id).first();return new Response(JSON.stringify(agent || {balance: 0,grade: "SENTINELLE"}),{headers: {...corsHeaders,"Content-Type": "application/json"}})}if (pathname === "/api/refill/submit" && request.method === "POST"){const d = await request.json();const txId = `RF-${Date.now().toString().slice(-6)}`;await env.DB.prepare("INSERT INTO refill_requests (id, agent_id, amount, proof_url, status) VALUES (?, ?, ?, ?, 'PENDING')").bind(txId,d.agentId,d.amount,d.proofBase64).run();return new Response(JSON.stringify({success: true,txId}),{headers: corsHeaders})}if (pathname === "/api/admin/refills" && request.method === "GET"){const pin = url.searchParams.get("pin");if (pin !== env.PIN_ADMIN) return new Response("UNAUTHORIZED",{status: 401,headers: corsHeaders});const requests = await env.DB.prepare("SELECT * FROM refill_requests WHERE status = 'PENDING' ORDER BY date DESC").all();return new Response(JSON.stringify(requests.results),{headers: {...corsHeaders,"Content-Type": "application/json"}})}if (pathname === "/api/admin/approve-refill" && request.method === "POST"){const{txId,pin}= await request.json();if (pin !== env.PIN_ADMIN) return new Response("UNAUTHORIZED",{status: 401,headers: corsHeaders});const req = await env.DB.prepare("SELECT * FROM refill_requests WHERE id = ?").bind(txId).first();if (!req) return new Response("NOT_FOUND",{status: 404,headers: corsHeaders});await env.DB.batch([env.DB.prepare("UPDATE resellers_pro SET balance = balance + ? WHERE agent_id = ?").bind(req.amount,req.agent_id),env.DB.prepare("UPDATE refill_requests SET status = 'VALIDÉ' WHERE id = ?").bind(txId),env.DB.prepare("INSERT INTO treasury_vault (agent_id, amount_in, yarmotek_central, transaction_type, reference_id) VALUES (?, ?, 0, 'REFILL_CREDIT', ?)").bind(req.agent_id,req.amount,txId)]);return new Response(JSON.stringify({success: true}),{headers: corsHeaders})}if (pathname === "/api/execute-seal" && request.method === "POST"){const d = await request.json();const split = calculateSovereignSplit(d.totalAmount,env);const certId = `SG-${Math.random().toString(36).substr(2,9).toUpperCase()}`;await env.DB.batch([env.DB.prepare("UPDATE resellers_pro SET balance = balance - ? WHERE agent_id = ?").bind(split.systemDebit,d.agentId),env.DB.prepare("INSERT INTO treasury_vault (agent_id, amount_in, yarmotek_central, transaction_type, reference_id) VALUES (?, ?, ?, 'SCELLAGE_CLIENT', ?)").bind(d.agentId,d.totalAmount,split.yarmotekPure,certId)]);return new Response(JSON.stringify({success: true,certId}),{headers: {...corsHeaders,"Content-Type": "application/json"}})}return await env.ASSETS.fetch(request)}catch (e){return new Response(JSON.stringify({error: "MATRIX_GATEWAY_ERROR",msg: e.message}),{status: 500,headers: corsHeaders})}}};{}
