import crypto from 'crypto';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';
const COOKIE='sc_admin_session';
const hash=(t:string)=>crypto.createHash('sha256').update(t).digest('hex');
export async function createSession(userId:number){const token=crypto.randomBytes(32).toString('hex'); const expiresAt=new Date(Date.now()+14*86400000); await prisma.session.create({data:{tokenHash:hash(token),userId,expiresAt}}); const c=await cookies(); c.set(COOKIE,token,{httpOnly:true,sameSite:'lax',secure:process.env.NODE_ENV==='production',path:'/',expires:expiresAt});}
export async function destroySession(){const c=await cookies(); const t=c.get(COOKIE)?.value; if(t) await prisma.session.deleteMany({where:{tokenHash:hash(t)}}); c.delete(COOKIE);}
export async function getCurrentAdmin(){const c=await cookies(); const t=c.get(COOKIE)?.value; if(!t)return null; const s=await prisma.session.findUnique({where:{tokenHash:hash(t)},include:{user:true}}); if(!s||s.expiresAt<new Date())return null; return s.user;}
export async function requireAdmin(){const u=await getCurrentAdmin(); if(!u) redirect('/admin/login'); return u;}
