import {env} from 'cloudflare:workers';
import {z} from 'zod';
import {contactDb} from '@/lib/contact-db';
const input=z.object({requestId:z.string().uuid(),name:z.string().trim().min(2).max(120),email:z.string().trim().email().max(254),company:z.string().trim().min(2).max(120),phone:z.string().trim().max(120).optional().default(''),message:z.string().trim().min(10).max(5000),website:z.string().max(1000).optional().default('')});
function reply(data:object,status=200){return Response.json(data,{status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}})}
export async function POST(request:Request){
 const origin=request.headers.get('origin');if(origin!==new URL(request.url).origin&&!['https://cas7.net','https://www.cas7.net','https://cas7-it-cloud-ai.upbeat-wren-5505.chatgpt.site'].includes(origin||''))return reply({error:'Request origin not allowed.'},403);
 if(!request.headers.get('content-type')?.includes('application/json'))return reply({error:'Send a JSON request.'},415);
 if(Number(request.headers.get('content-length')||0)>14000)return reply({error:'Request is too large.'},413);
 let raw:string;try{raw=await request.text();if(raw.length>14000)return reply({error:'Request is too large.'},413)}catch{return reply({error:'Unable to read request.'},400)}
 let parsed;try{parsed=input.safeParse(JSON.parse(raw))}catch{return reply({error:'Invalid request.'},400)}
 if(!parsed.success)return reply({error:'Please check the required fields and try again.'},400);
 const data=parsed.data;if(data.website)return reply({error:'Unable to process this request. Please call or email Cas7.'},400);
 try{const db=contactDb();const existing=await db.prepare('SELECT id FROM inquiries WHERE id = ? AND email = ?').bind(data.requestId,data.email).first();if(existing)return reply({ok:true});
 const now=Date.now();const ip=request.headers.get('cf-connecting-ip')||'local';const digest=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(new Date().toISOString().slice(0,10)+ip));const ipHash=Array.from(new Uint8Array(digest)).map(b=>b.toString(16).padStart(2,'0')).join('');
 const count=await db.prepare('SELECT COUNT(*) AS count FROM inquiries WHERE ip_hash = ? AND created_at > ?').bind(ipHash,now-900000).first<{count:number}>();if((count?.count||0)>=5)return reply({error:'Too many requests. Please wait a few minutes or call 724-714-5829.'},429);
 await db.prepare('INSERT INTO inquiries (id,name,email,company,phone,message,created_at,ip_hash,notification_status) VALUES (?,?,?,?,?,?,?,?,?)').bind(data.requestId,data.name,data.email,data.company,data.phone,data.message,now,ipHash,'not_configured').run();
 const config=env as typeof env&{RESEND_API_KEY?:string;CONTACT_FROM_EMAIL?:string};
 if(config.RESEND_API_KEY&&config.CONTACT_FROM_EMAIL){let status='failed';try{const mail=await fetch('https://api.resend.com/emails',{method:'POST',headers:{'Authorization':`Bearer ${config.RESEND_API_KEY}`,'Content-Type':'application/json','Idempotency-Key':data.requestId},body:JSON.stringify({from:config.CONTACT_FROM_EMAIL,to:['info@cas7.net'],reply_to:data.email,subject:'New Cas7 website inquiry',text:`Name: ${data.name}\nCompany: ${data.company}\nEmail: ${data.email}\nPhone: ${data.phone}\n\n${data.message}`}),signal:AbortSignal.timeout(7000)});status=mail.ok?'sent':'failed';}catch{console.error('Contact email notification failed');}await db.prepare('UPDATE inquiries SET notification_status = ? WHERE id = ?').bind(status,data.requestId).run();}
 return reply({ok:true});
 }catch{console.error('Contact request could not be completed');return reply({error:'Unable to save your request. Please try again or contact info@cas7.net.'},503)}
}
