import { prisma } from '@/lib/prisma';
const BASE='https://schachde-apps.liga.nu/dsbwertungsportal/rs/dwz/dwzliste/persons'; const CLUB='83210';
type P={uuid?:string;nuLigaPersonId?:string;firstname?:string;lastname?:string;rating?:number|null;index?:number|null;memberships?:Array<{clubVkz?:string}>};
function list(j:unknown):P[]{if(Array.isArray(j))return j as P[];if(j&&typeof j==='object'){const o=j as Record<string,unknown>;if(Array.isArray(o.data))return o.data as P[];return [o as P]}return[]}
export async function syncAllDwz(){const players=await prisma.player.findMany();const results=[] as Array<{id:number;ok:boolean;message:string}>;for(const p of players){try{const url=p.nuLigaPersonId?`${BASE}/${encodeURIComponent(p.nuLigaPersonId)}`:`${BASE}?lastname=${encodeURIComponent(p.lastName)}&firstname=${encodeURIComponent(p.firstName)}`;const r=await fetch(url,{headers:{Accept:'application/json'},cache:'no-store'});if(!r.ok)throw new Error(`DSB ${r.status}`);const people=list(await r.json());const person=people.find(x=>x.memberships?.some(m=>String(m.clubVkz)===CLUB))??people[0];if(!person){results.push({id:p.id,ok:false,message:'Nicht gefunden'});continue;}await prisma.player.update({where:{id:p.id},data:{dwz:typeof person.rating==='number'?person.rating:null,dwzIndex:typeof person.index==='number'?person.index:null,nuLigaPersonId:person.nuLigaPersonId??p.nuLigaPersonId,dsbUuid:person.uuid??p.dsbUuid,lastSyncedAt:new Date()}});results.push({id:p.id,ok:true,message:`DWZ ${person.rating??'—'}`});}catch(e){results.push({id:p.id,ok:false,message:e instanceof Error?e.message:'Fehler'});}}return results;}
