import 'server-only';
import fs from 'node:fs';
import path from 'node:path';
import {randomUUID,scryptSync,randomBytes,timingSafeEqual,createHmac,createHash} from 'node:crypto';
import type {Collection,Project,UserView} from './models';
import type {NextRequest} from 'next/server';

export type StoredUser=UserView&{sessionVersion?:number;passwordReset?:{hash:string;expiresAt:number;requestedAt:number};safetyAcceptedAt?:string;passwordHash:string;favorites:string[];recent:string[];referralCode?:string;referredByUserId?:string;discord?:{id:string;username:string};appPreferences?:Record<string,{device:'phone'|'desktop';autoPreview:boolean}>};
type Store={users:StoredUser[];projects:Project[];collections:Collection[]};
const dbPath=path.join(process.cwd(),'.local-data','store.json');
function load():Store{try{const s=JSON.parse(fs.readFileSync(dbPath,'utf8')) as Store;return{...s,users:s.users||[],projects:s.projects||[],collections:s.collections||[]}}catch{return{users:[],projects:[],collections:[]}}}
function save(s:Store){fs.mkdirSync(path.dirname(dbPath),{recursive:true});const file=dbPath+'.tmp';fs.writeFileSync(file,JSON.stringify(s,null,2),{mode:0o600});fs.renameSync(file,dbPath)}
export function publicUser(u:StoredUser):UserView{const {id,name,email,createdAt,handle}=u;return{id,name,email,createdAt,handle}}
function hash(password:string,salt?:string){const s=salt||randomBytes(16).toString('hex');return s+':'+scryptSync(password,s,64).toString('hex')}
function verify(password:string,stored:string){try{const [salt,hex]=stored.split(':');return timingSafeEqual(Buffer.from(hex,'hex'),Buffer.from(hash(password,salt).split(':')[1],'hex'))}catch{return false}}
function newReferralCode(users:StoredUser[]){let code='';do{code=randomBytes(5).toString('hex').toUpperCase()}while(users.some(u=>u.referralCode===code));return code}
function ensureReferralCodes(s:Store){let changed=false;for(const u of s.users)if(!u.referralCode){u.referralCode=newReferralCode(s.users);changed=true}if(changed)save(s)}
export function register(name:string,email:string,password:string,referralCode?:string){const s=load();const e=email.toLowerCase().trim();if(s.users.some(u=>u.email===e))return{error:'An account with that email already exists.'};ensureReferralCodes(s);const inviter=s.users.find(u=>u.referralCode?.toUpperCase()===referralCode?.trim().toUpperCase()&&u.email!==e);const u:StoredUser={id:randomUUID(),name:name.trim(),email:e,passwordHash:hash(password),favorites:[],recent:[],referralCode:newReferralCode(s.users),referredByUserId:inviter?.id,createdAt:new Date().toISOString(),safetyAcceptedAt:new Date().toISOString()};s.users.push(u);save(s);return{user:publicUser(u)}}
export function getReferralSummary(userId:string){const s=load();ensureReferralCodes(s);const user=s.users.find(u=>u.id===userId);if(!user)return null;return{code:user.referralCode,referrals:s.users.filter(u=>u.referredByUserId===userId).length}}
export function login(email:string,password:string){const u=load().users.find(u=>u.email===email.toLowerCase().trim());return u&&verify(password,u.passwordHash)?publicUser(u):null}
/**
 * A reset token is generated using a cryptographic RNG. Only a SHA-256 hash is
 * written to the private account store. It expires after one hour and is
 * consumed once. A user can request at most one token every two minutes.
 * The public endpoint always returns a generic response for unknown addresses.
 */
export function issuePasswordReset(email:string):{token:string;recipient:string;userId:string}|null{
 const s=load();const user=s.users.find(u=>u.email===email.trim().toLowerCase());if(!user)return null;
 const now=Date.now();if(user.passwordReset&&now-user.passwordReset.requestedAt<2*60*1000)return null;
 const token=randomBytes(32).toString('hex');user.passwordReset={hash:createHash('sha256').update(token).digest('hex'),requestedAt:now,expiresAt:now+60*60*1000};save(s);
 return{token,recipient:user.email,userId:user.id};
}
/** Remove only the issued token when email delivery fails, without touching the account. */
export function revokePasswordReset(userId:string,token:string){
 const s=load();const u=s.users.find(x=>x.id===userId);if(!u?.passwordReset)return;
 const candidate=createHash('sha256').update(token).digest('hex');
 if(timingSafeEqual(Buffer.from(candidate,'hex'),Buffer.from(u.passwordReset.hash,'hex'))){delete u.passwordReset;save(s)}
}
/** Complete a reset without signing the caller in. All old sessions are revoked. */
export function consumePasswordReset(token:string,newPassword:string):{userId:string;email:string}|null{
 if(!/^[0-9a-f]{64}$/i.test(token)||newPassword.length<10||newPassword.length>128)return null;
 const s=load(),candidate=Buffer.from(createHash('sha256').update(token).digest('hex'),'hex'),now=Date.now();
 const u=s.users.find(user=>{
  const item=user.passwordReset;if(!item||item.expiresAt<=now||!(/^[0-9a-f]{64}$/i.test(item.hash)))return false;
  return timingSafeEqual(candidate,Buffer.from(item.hash,'hex'));
 });
 if(!u)return null;
 u.passwordHash=hash(newPassword);delete u.passwordReset;u.sessionVersion=(u.sessionVersion||0)+1;save(s);
 return {userId:u.id,email:u.email};
}

function secret(){const v=process.env.AUTH_SECRET;if(process.env.NODE_ENV==='production'&&(!v||v.length<32))throw Error('AUTH_SECRET needs a 32+ character value in production');return v||'dev-only-local-secret-DO-NOT-DEPLOY-REPLACE-ME'}
export function createSession(userId:string){const version=load().users.find(u=>u.id===userId)?.sessionVersion||0;const body=Buffer.from(JSON.stringify({sub:userId,ver:version,exp:Date.now()+7*24*60*60*1000})).toString('base64url');const signature=createHmac('sha256',secret()).update(body).digest('base64url');return body+'.'+signature}
export function sessionUser(req:NextRequest):UserView|null{const cookie=req.cookies.get('larpdevice_session')?.value;if(!cookie)return null;const [body,sig]=cookie.split('.');if(!body||!sig)return null;const expected=createHmac('sha256',secret()).update(body).digest('base64url');const a=Buffer.from(sig),b=Buffer.from(expected);if(a.length!==b.length||!timingSafeEqual(a,b))return null;try{const p=JSON.parse(Buffer.from(body,'base64url').toString()) as {sub:string;ver?:number;exp:number};if(p.exp<Date.now())return null;const u=load().users.find(x=>x.id===p.sub);return u&&(p.ver??0)===(u.sessionVersion??0)?publicUser(u):null}catch{return null}}
export function originAllowed(req:NextRequest){
  const rawOrigin=req.headers.get('origin');if(!rawOrigin)return true;
  try{
    const origin=new URL(rawOrigin);
    if(origin.protocol!=='http:'&&origin.protocol!=='https:')return false;
    const configured=new URL(process.env.APP_URL||req.nextUrl.origin);
    const forwardedHost=(req.headers.get('x-forwarded-host')||req.headers.get('host')||req.nextUrl.host).split(',')[0].trim();
    const forwarded=new URL(`http://${forwardedHost}`);
    const normalize=(host:string)=>host.toLowerCase().replace(/^www\./,'');
    const expectedHosts=new Set([normalize(configured.hostname),normalize(forwarded.hostname)]);
    if(!expectedHosts.has(normalize(origin.hostname)))return false;
    const expectedPorts=new Set([configured.port,forwarded.port].filter(Boolean));
    return !origin.port||expectedPorts.has(origin.port);
  }catch{return false}
}
export function getProjects(userId:string){return load().projects.filter(p=>p.userId===userId).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))}
/** Owner console: list only saved visual connections, not private project payloads. */
export function listProjectUiBindings(){return load().projects.filter(p=>p.data.uiBindings&&Object.keys(p.data.uiBindings).length>0).map(p=>({projectId:p.id,name:p.name,slug:p.templateSlug,ownerId:p.userId,bindings:p.data.uiBindings||{}}));}
export function getProject(id:string){return load().projects.find(p=>p.id===id)||null}
export function createProject(project:Project){const s=load();s.projects.push(project);save(s);return project}
export function updateProject(id:string,userId:string,patch:Partial<Pick<Project,'name'|'data'|'published'|'lastOpenedAt'>>){const s=load();const p=s.projects.find(p=>p.id===id&&p.userId===userId);if(!p)return null;Object.assign(p,patch,{updatedAt:new Date().toISOString()});save(s);return p}
export function deleteProject(id:string,userId:string){const s=load();const i=s.projects.findIndex(p=>p.id===id&&p.userId===userId);if(i<0)return false;s.projects.splice(i,1);save(s);return true}
export function getFavorites(userId:string){return load().users.find(u=>u.id===userId)?.favorites||[]}
export function setFavorite(userId:string,slug:string,enabled:boolean){const s=load();const u=s.users.find(u=>u.id===userId);if(!u)return[];u.favorites=enabled?[...new Set([...u.favorites,slug])]:u.favorites.filter(x=>x!==slug);save(s);return u.favorites}
export function getRecent(userId:string){return load().users.find(u=>u.id===userId)?.recent||[]}
export function addRecent(userId:string,slug:string){const s=load();const u=s.users.find(u=>u.id===userId);if(!u)return;u.recent=[slug,...u.recent.filter(x=>x!==slug)].slice(0,20);save(s)}
export function getCollections(userId:string){return load().collections.filter(c=>c.userId===userId)}
export function createCollection(c:Collection){const s=load();s.collections.push(c);save(s);return c}
export function updateCollection(userId:string,id:string,patch:Partial<Collection>){const s=load();const c=s.collections.find(c=>c.userId===userId&&c.id===id);if(!c)return null;if(patch.name!==undefined)c.name=patch.name;if(patch.description!==undefined)c.description=patch.description;if(patch.slugs!==undefined)c.slugs=patch.slugs;save(s);return c}
export function removeCollection(userId:string,id:string){const s=load();const n=s.collections.length;s.collections=s.collections.filter(c=>!(c.userId===userId&&c.id===id));if(s.collections.length===n)return false;save(s);return true}
export function updateProfile(userId:string,name:string){const s=load();const u=s.users.find(u=>u.id===userId);if(!u)return null;u.name=name;save(s);return publicUser(u)}

/** One server snapshot keeps initial hydration to one HTTP request rather than five. */
export function getAccountSnapshot(req:NextRequest){
  const user=sessionUser(req);
  if(!user)return {user:null,projects:[],favorites:[],collections:[],recent:[]};
  const s=load();
  const stored=s.users.find(x=>x.id===user.id);
  return {
    user,
    projects:s.projects.filter(x=>x.userId===user.id).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt)),
    favorites:stored?.favorites||[],
    collections:s.collections.filter(x=>x.userId===user.id),
    recent:stored?.recent||[]
  };
}

export function getStoredUser(userId:string){return load().users.find(u=>u.id===userId)||null}
export function findReferralUser(code:string){return load().users.find(u=>u.referralCode?.toUpperCase()===code.toUpperCase())||null}
export function referralOwnerForCustomer(customerId:string){const customer=getStoredUser(customerId);return customer?.referredByUserId?getStoredUser(customer.referredByUserId):null}
export function listStudioUsers(){const s=load();return s.users.map(u=>({id:u.id,name:u.name,email:u.email,createdAt:u.createdAt,referralCode:u.referralCode||'',referrals:s.users.filter(v=>v.referredByUserId===u.id).length}));}
export function setUserReferralCode(userId:string,raw:string){const code=raw.trim().toUpperCase();if(!/^[A-Z0-9_-]{4,24}$/.test(code))return {error:'Code must use 4–24 letters, numbers, underscore or dash'};const s=load();const u=s.users.find(x=>x.id===userId);if(!u)return {error:'User not found'};if(s.users.some(x=>x.id!==userId&&x.referralCode?.toUpperCase()===code))return {error:'Code already assigned'};u.referralCode=code;save(s);return {code};}
export function setProfileEmail(userId:string,email:string,password:string){const s=load();const user=s.users.find(u=>u.id===userId);if(!user||!verify(password,user.passwordHash))return {error:'Incorrect password'};const normalized=email.trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized)||normalized.length>254)return {error:'Invalid email address'};if(s.users.some(u=>u.id!==userId&&u.email===normalized))return {error:'Email already used'};user.email=normalized;delete user.passwordReset;save(s);return {user:publicUser(user)};}
export function deleteUser(userId:string,password:string){const s=load();const user=s.users.find(u=>u.id===userId);if(!user||!verify(password,user.passwordHash))return false;s.users=s.users.filter(x=>x.id!==userId);s.projects=s.projects.filter(x=>x.userId!==userId);s.collections=s.collections.filter(x=>x.userId!==userId);for(const other of s.users)if(other.referredByUserId===userId)delete other.referredByUserId;save(s);return true;}
export function getUserPreferences(userId:string){return getStoredUser(userId)?.appPreferences||{};}
export function setAppPreferences(userId:string,slug:string,patch:{device:'phone'|'desktop';autoPreview:boolean}){const s=load();const u=s.users.find(x=>x.id===userId);if(!u)return null;u.appPreferences={...u.appPreferences,[slug]:patch};save(s);return patch;}
export function setDiscordAccount(userId:string,account:{id:string;username:string}|null){const s=load();const u=s.users.find(x=>x.id===userId);if(!u)return null;if(account)u.discord=account;else delete u.discord;save(s);return account;}
export function getAccountConnections(userId:string){return {discord:getStoredUser(userId)?.discord||null};}

/** One unique community handle per account; values are server-validated, never free-form HTML. */
export function claimHandle(userId:string,raw:string){
 const handle=raw.trim().replace(/^@/,'').toLowerCase();
 if(!/^[a-z][a-z0-9_]{2,23}$/.test(handle))return {error:'Use 3–24 lowercase letters, numbers, or underscores, starting with a letter.'};
 if(new Set(['admin','owner','support','moderator','larpdevice','cashapp','cash_app','system','security','help','official','staff','billing']).has(handle))return {error:'This handle is reserved.'};
 const s=load();const u=s.users.find(x=>x.id===userId);if(!u)return {error:'Account not found'};
 if(s.users.some(x=>x.id!==userId&&x.handle?.toLowerCase()===handle))return {error:'This handle is already taken'};
 const prior=u.handle||null;u.handle=handle;save(s);return {handle,prior};
}
