import { db,hashPassword,jsonError,sha256,uid } from "@/lib/server";import { env } from "cloudflare:workers";
export async function POST(request:Request){const x=await request.json() as {email?:string,password?:string,setupToken?:string,name?:string};if(!x.email||!x.password)return jsonError("Email and password are required.");if(x.password.length<12)return jsonError("Password must contain at least 12 characters.");const count=await db().prepare("SELECT COUNT(*) AS n FROM admins").first<{n:number}>();if(!count?.n){const expected=(env as unknown as Record<string,string>).ADMIN_SETUP_TOKEN;if(!expected||x.setupToken!==expected)return jsonError("A valid one-time setup token is required.",403);const salt=crypto.randomUUID();await db().prepare("INSERT INTO admins(id,email,name,password_hash,salt,role) VALUES(?,?,?,?,?,'super_admin')").bind(uid("adm_"),x.email.toLowerCase(),x.name||"Conference Administrator",await hashPassword(x.password,salt),salt).run()}const admin=await db().prepare("SELECT * FROM admins WHERE email=? AND active=1").bind(x.email.toLowerCase()).first<Record<string,string>>();if(!admin||await hashPassword(x.password,admin.salt)!==admin.password_hash)return jsonError("Invalid email or password.",401);const token=crypto.randomUUID()+crypto.randomUUID();await db().prepare("INSERT INTO admin_sessions(id,admin_id,token_hash,expires_at) VALUES(?,?,?,datetime('now','+8 hours'))").bind(uid("ses_"),admin.id,await sha256(token)).run();await db().prepare("UPDATE admins SET last_login_at=CURRENT_TIMESTAMP WHERE id=?").bind(admin.id).run();return new Response(JSON.stringify({ok:true}),{headers:{"content-type":"application/json","set-cookie":`ofm_admin=${encodeURIComponent(token)}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=28800`}})}
export async function DELETE(request:Request){const cookie=request.headers.get("cookie")||"";const token=cookie.match(/(?:^|; )ofm_admin=([^;]+)/)?.[1];if(token)await db().prepare("DELETE FROM admin_sessions WHERE token_hash=?").bind(await sha256(decodeURIComponent(token))).run();return new Response(JSON.stringify({ok:true}),{headers:{"content-type":"application/json","set-cookie":"ofm_admin=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0"}})}
