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

const isProduction = process.env.NODE_ENV === 'production';

if (isProduction && !process.env.JWT_SECRET) {
  throw new Error('[Auth] JWT_SECRET environment variable is required in production. Set it before deploying.');
}

if (!isProduction && !process.env.JWT_SECRET) {
  console.warn('[Auth] JWT_SECRET not set — using default dev key. Set JWT_SECRET for production!');
}

const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'restroagent-dev-secret-key-not-for-production');
export const COOKIE_NAME = 'restroagent_session';

export interface SessionPayload {
  userId: string;
  email: string;
  role: string;
  restaurantId: string | null;
  branchId: string | null;
}

export async function createSessionToken(payload: SessionPayload): Promise<string> {
  return createSession(payload);
}

export async function createSession(payload: SessionPayload): Promise<string> {
  return new SignJWT({ ...payload })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('7d')
    .sign(JWT_SECRET);
}

export async function verifySession(token: string): Promise<SessionPayload | null> {
  try {
    const { payload } = await jwtVerify(token, JWT_SECRET);
    return payload as unknown as SessionPayload;
  } catch {
    return null;
  }
}

export async function getSession(): Promise<SessionPayload | null> {
  const cookieStore = await cookies();
  const token = cookieStore.get(COOKIE_NAME)?.value;
  if (!token) return null;
  return verifySession(token);
}
