import { db } from "./db.ts";

export const TOKEN_TTL_DAYS = parseInt(process.env.TOKEN_TTL_DAYS ?? "30");

export const issueToken = async (userId: number): Promise<string> => {
    const token = crypto.randomUUID();
    const expiresAt = new Date(Date.now() + TOKEN_TTL_DAYS * 86_400_000)
        .toISOString()
        .replace("T", " ")
        .slice(0, 19);
    await db`INSERT INTO auth_tokens (user_id, token, expires_at) VALUES (${userId}, ${token}, ${expiresAt})`;
    return token;
};

export const validateToken = async (token: string): Promise<number | null> => {
    const [row] = await db`
        SELECT user_id FROM auth_tokens
        WHERE token = ${token} AND expires_at > datetime('now')
    `;
    if (!row) return null;

    const expiresAt = new Date(Date.now() + TOKEN_TTL_DAYS * 86_400_000)
        .toISOString()
        .replace("T", " ")
        .slice(0, 19);
    await db`UPDATE auth_tokens SET expires_at = ${expiresAt} WHERE token = ${token}`;

    return row.user_id as number;
};

export const requireAuth = async (req: Request): Promise<{ userId: number } | Response> => {
    const auth = req.headers.get("Authorization");
    if (!auth?.startsWith("Bearer ")) {
        return Response.json({ error: "Unauthorized" }, { status: 401 });
    }
    const token = auth.slice(7);
    const userId = await validateToken(token);
    if (userId === null) {
        return Response.json({ error: "Invalid or expired token" }, { status: 401 });
    }
    return { userId };
};
