import { SignJWT, jwtVerify } from 'jose';
import { cookies } from 'next/headers';

export const ADMIN_SESSION_COOKIE = 'admin_session';
const SESSION_DURATION_SECONDS = 60 * 60 * 24 * 7; // 7 days

// Entirely separate from customer auth (src/lib/auth.ts) — different cookie,
// different secret, no shared code path. Logging into one never grants access
// to the other. No database table needed: there's still just one admin
// identity, ADMIN_USER/ADMIN_PASSWORD from .env, checked in the login action.
function adminSecretKey() {
  const secret = process.env.ADMIN_SESSION_SECRET;
  if (!secret) throw new Error('ADMIN_SESSION_SECRET is not set — add it to .env.');
  return new TextEncoder().encode(secret);
}

export async function createAdminSession() {
  const token = await new SignJWT({ role: 'admin' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime(`${SESSION_DURATION_SECONDS}s`)
    .sign(adminSecretKey());

  cookies().set(ADMIN_SESSION_COOKIE, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
    maxAge: SESSION_DURATION_SECONDS,
  });
}

export function clearAdminSession() {
  cookies().delete(ADMIN_SESSION_COOKIE);
}

export async function isAdminAuthenticated() {
  const token = cookies().get(ADMIN_SESSION_COOKIE)?.value;
  if (!token) return false;

  try {
    await jwtVerify(token, adminSecretKey());
    return true;
  } catch {
    return false;
  }
}
