import 'server-only';
import fs from 'node:fs';
import path from 'node:path';
import {randomBytes,createHash} from 'node:crypto';

type LinkRecord={projectId:string;userId:string;templateSlug:string;tokenHash:string;token:string;createdAt:string;revokedAt?:string;deletedAt?:string};
type LinkEvent={date:string;action:'created'|'rotated'|'revoked'|'deleted';projectId:string;userId:string;templateSlug:string;linkId:string};
type Store={links:LinkRecord[];events:LinkEvent[]};
const file=path.join(process.cwd(),'.local-data','live-links.json');
function read():Store{try{const v=JSON.parse(fs.readFileSync(file,'utf8')) as Store;return{links:v.links||[],events:v.events||[]}}catch{return{links:[],events:[]}}}
function write(s:Store){fs.mkdirSync(path.dirname(file),{recursive:true});const tmp=file+'.tmp';fs.writeFileSync(tmp,JSON.stringify(s,null,2),{mode:0o600});fs.renameSync(tmp,file)}
const digest=(token:string)=>createHash('sha256').update(token).digest('hex');
export function issueLiveLink(projectId:string,userId:string,templateSlug:string){
 const s=read(),now=new Date().toISOString();
 for(const link of s.links.filter(l=>l.projectId===projectId&&!l.revokedAt&&!l.deletedAt)){
  link.revokedAt=now;s.events.push({date:now,action:'rotated',projectId,userId,templateSlug,linkId:link.tokenHash.slice(0,12)});
 }
 const token=randomBytes(24).toString('base64url'),tokenHash=digest(token);
 s.links.push({projectId,userId,templateSlug,tokenHash,token,createdAt:now});
 s.events.push({date:now,action:'created',projectId,userId,templateSlug,linkId:tokenHash.slice(0,12)});
 write(s);return{token,url:'/l/'+token,createdAt:now};
}
export function activeLiveLink(projectId:string,userId:string){const link=read().links.find(l=>l.projectId===projectId&&l.userId===userId&&!l.revokedAt&&!l.deletedAt);return link?{url:'/l/'+link.token,createdAt:link.createdAt}:null}
export function lookupLiveLink(token:string){if(!/^[A-Za-z0-9_-]{32}$/.test(token))return null;return read().links.find(l=>l.tokenHash===digest(token))||null}
export function deleteProjectLinks(projectId:string,userId:string){const s=read(),now=new Date().toISOString();let changed=false;for(const link of s.links.filter(l=>l.projectId===projectId&&l.userId===userId&&!l.deletedAt)){link.deletedAt=now;s.events.push({date:now,action:'deleted',projectId,userId,templateSlug:link.templateSlug,linkId:link.tokenHash.slice(0,12)});changed=true}if(changed)write(s)}
export function listLinkEvents(){return read().events.slice(-500).reverse()}
