---
import Layout from "../../layouts/Layout.astro";
import { getAllAccessTokens } from "../../lib/db/accessTokens";
import { getUserByAccessToken } from "../../lib/db/users";

const tokens = await getAllAccessTokens();

const type = {
    "A": "Authorization",
    "X": "Master Key"
}
---

<Layout title="Access tokens">
    <h1>Access tokens</h1>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>Type</th>
                <th>Username</th>
                <th>Entropy hash</th>
                <th>Created</th>
                <th>Expires</th>
                <th>Created from</th>
                <th>Validity</th>
            </tr>
        </thead>
        <tbody>
            {tokens.map(async token => <tr>
                <td>{token._id}</td>
                <td>{type[token.type] ?? `Other`}</td>
                <td>{(await getUserByAccessToken(token))?.username}</td>
                <td>{token.entropy}</td>
                <td>{token.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ")}</td>
                <td>{token.expiresAt?.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ") ?? "Never"}</td>
                <td>{token.createdFrom}</td>
                <td>{token.expiresAt !== null && Date.now() > token.expiresAt.getTime() ? <span style="color: red;">Expired {Math.floor((Date.now() - token.expiresAt.getTime()) / 1000 / 60)} minutes ago</span> : Date.now() < token.createdAt.getTime() ? <span style="color: cyan;">TimeTravelException (check in {Math.floor((token.createdAt.getTime() - Date.now()) / 1000 / 60)} minutes)</span> : <span style="color: lime;">Valid for{token.expiresAt === null ? "ever" : ` ${Math.floor((token.expiresAt.getTime() - Date.now()) / 1000 / 60)} minutes`}</span>}</td>
            </tr>)}
        </tbody>
    </table>
</Layout>

<style>
* {
    color: white;
    font-family: monospace;
    font-size: 14px;
}
</style>