import { NextRequest } from 'next/server';
import { prisma } from '@/lib/prisma';
import crypto from 'crypto';

/**
 * Executive display-token auth — the login-less credential for the Executive
 * Command dashboard: admin-minted, device-locked, expiry-bound `ApiToken` rows scoped
 * `executive_display`. Metadata lives in the dedicated columns (these tokens
 * are new — no legacy pipe-encoded rows to fall back to).
 *
 * Replaces the old `executive_session` JWT handoff, which minted a token for
 * ANY authenticated user with no role claim (a privilege-escalation path —
 * see docs/technical-assessment-punch-list.md #1). Minting now requires ADMIN.
 */
export const EXEC_SCOPE = 'executive_display';
export const EXEC_TOKEN_COOKIE = 'exec_display_token';
export const EXEC_DEVICE_COOKIE = 'exec_device_id';
/** 30-day rolling cookie, refreshed on each verify (mirrors NOC). */
export const EXEC_TOKEN_EXPIRY = 30 * 24 * 60 * 60;

export function hashExecToken(token: string): string {
    return crypto.createHash('sha256').update(token).digest('hex');
}

export interface ExecutiveDisplaySession {
    displayName: string;
    countryId: number | null;
    deviceName: string | null;
}

/**
 * Verify the exec display cookie pair against a live, non-revoked, non-expired,
 * device-locked token. Returns null on any failure (caller treats as
 * unauthenticated). Read-only — no mutation.
 */
export async function getExecutiveDisplaySession(req: NextRequest): Promise<ExecutiveDisplaySession | null> {
    const token = req.cookies.get(EXEC_TOKEN_COOKIE)?.value;
    const currentDeviceId = req.cookies.get(EXEC_DEVICE_COOKIE)?.value;
    if (!token) return null;

    const apiToken = await prisma.apiToken.findFirst({
        where: { tokenHash: hashExecToken(token), scopes: EXEC_SCOPE, revokedAt: null },
    });
    if (!apiToken) return null;

    if (apiToken.expiresAt && new Date(apiToken.expiresAt) < new Date()) return null;

    // Device lock: once bound, the cookie's device id must match.
    if (apiToken.lockedDeviceId && apiToken.lockedDeviceId !== currentDeviceId) return null;

    return {
        displayName: apiToken.displayName || 'Executive Display',
        countryId: apiToken.countryId ?? null,
        deviceName: apiToken.deviceName ?? null,
    };
}
