import {NextRequest,NextResponse} from 'next/server';
import {getProject,sessionUser,updateProject,originAllowed} from '@/lib/server-store';
import {isStudioAdmin} from '@/lib/studio-store';
import {canUseApp} from '@/lib/billing-store';
import {getCombinedNativeSpec,validateNativePatch} from '@/lib/native-capture-editor';
import {logFromRequest} from '@/lib/activity-log';
export const runtime='nodejs';
export const dynamic='force-dynamic';
type Ctx={params:Promise<{id:string}>};
function lookup(req:NextRequest,id:string){
 const user=sessionUser(req);if(!user)return {error:'Sign in to change this LARP.',status:401} as const;
 const project=getProject(id);if(!project||project.userId!==user.id)return {error:'This LARP does not belong to your account.',status:404} as const;
 if(!isStudioAdmin(req)&&!canUseApp(user.id,project.templateSlug))return {error:'An active plan is required to edit this LARP.',status:402} as const;
 const spec=getCombinedNativeSpec(project.templateSlug);
 if(!spec)return {error:'This app has no captured built-in settings editor. Use hold-to-edit instead.',status:404} as const;
 return {user,project,spec};
}
export async function GET(req:NextRequest,{params}:Ctx){
 const {id}=await params;const r=lookup(req,id);
 if('error' in r)return NextResponse.json({error:r.error},{status:r.status});
 const values=r.project.data.nativeSettings||{};
 return NextResponse.json({title:r.spec.title,fields:r.spec.fields.map(f=>({...f,value:Object.hasOwn(values,f.key)?values[f.key]:f.value})),supported:true},{headers:{'Cache-Control':'no-store'}});
}
export async function PATCH(req:NextRequest,{params}:Ctx){
 const {id}=await params;const r=lookup(req,id);
 if('error' in r)return NextResponse.json({error:r.error},{status:r.status});
 if(!originAllowed(req))return NextResponse.json({error:'Invalid request origin.'},{status:403});
 const raw=await req.json().catch(()=>null);
 // Captured editors sometimes include transport-only keys that are not UI settings.
 const patch=raw&&typeof raw==='object'&&!Array.isArray(raw)?Object.fromEntries(Object.entries(raw as Record<string,unknown>).filter(([key])=>!['source','via','shown'].includes(key))):raw;
 const validated=validateNativePatch(r.spec,patch);
 if(!validated.valid)return NextResponse.json({error:validated.error},{status:400});
 const updated=updateProject(id,r.user.id,{data:{...r.project.data,nativeSettings:{...(r.project.data.nativeSettings||{}),...validated.changes}}});
 if(updated)logFromRequest(req,{category:'larp',action:'larp.native-settings.updated',targetType:'larp',targetId:id,summary:`Updated built-in settings for ${r.project.name}`,fields:Object.keys(validated.changes),needsReview:false,link:'/developer/activity'});
 return updated?NextResponse.json({ok:true,updatedAt:updated.updatedAt},{headers:{'Cache-Control':'no-store'}}):NextResponse.json({error:'Could not save changes.'},{status:404});
}
