// Reference implementation. Configure SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY and TURNSTILE_SECRET.
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
const headers={'content-type':'application/json','access-control-allow-origin':'*'};
Deno.serve(async(req)=>{
  if(req.method==='OPTIONS')return new Response(null,{headers});
  if(req.method!=='POST')return new Response(JSON.stringify({error:'Method not allowed'}),{status:405,headers});
  try{
    const body=await req.json();
    const pageKey=String(body.pageKey||'').trim(),displayName=String(body.displayName||'').trim(),comment=String(body.body||'').trim(),locale=body.locale==='ja'?'ja':'en';
    if(pageKey.length<3||pageKey.length>180||displayName.length<1||displayName.length>80||comment.length<1||comment.length>1200)throw new Error('Invalid fields');
    const token=String(body.turnstileToken||'');
    const verify=await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify',{method:'POST',headers:{'content-type':'application/x-www-form-urlencoded'},body:new URLSearchParams({secret:Deno.env.get('TURNSTILE_SECRET')||'',response:token})});
    const verification=await verify.json();if(!verification.success)throw new Error('Bot verification failed');
    const supabase=createClient(Deno.env.get('SUPABASE_URL')||'',Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')||'');
    const {error}=await supabase.from('comments').insert({page_key:pageKey,display_name:displayName,body:comment,website:body.website||null,locale,status:'pending'});if(error)throw error;
    return new Response(JSON.stringify({ok:true,status:'pending'}),{status:202,headers});
  }catch(error){return new Response(JSON.stringify({error:String(error?.message||error)}),{status:400,headers})}
});
