import useDatabase from "~/composables/useDatabase";
import { usersDataTable, userSessionsTable } from "~/db/schema";
import { eq, and, sql, lte } from "drizzle-orm";
import { refreshSessionFromDB } from "../utils/user";

const monthAsMs = 60 * 60 * 24 * 30 * 1000;

export default defineNitroPlugin(() => {
    const db = useDatabase();
    
    sessionHooks.hook('fetch', async (session, event) => {
        db.delete(userSessionsTable).where(and(eq(userSessionsTable.user_id, sql.placeholder('id')), lte(userSessionsTable.timestamp, sql.placeholder('timestamp')))).prepare().run({ id: session.user.id, timestamp: Math.round((Date.now() - monthAsMs) / 1000) });
        const result = db.select({ timestamp: userSessionsTable.timestamp }).from(userSessionsTable).where(and(eq(userSessionsTable.id, sql.placeholder('id')), eq(userSessionsTable.user_id, sql.placeholder('user_id')))).prepare().get({ id: session.id, user_id: session.user.id });

        if(!result)
        {
            await clearUserSession(event);
            throw createError({ statusCode: 401, message: 'Unauthorized' });
        }
        else
        {
            db.update(userSessionsTable).set({
                timestamp: new Date(),
            }).where(and(eq(userSessionsTable.id, sql.placeholder('id')), eq(userSessionsTable.user_id, sql.placeholder('user_id')))).prepare().run({ id: session.id, user_id: session.user.id });
            
            db.update(usersDataTable).set({
                lastTimestamp: new Date(),
            }).where(eq(usersDataTable.id, sql.placeholder('user_id'))).prepare().run({ id: session.id, user_id: session.user.id });
            
            await refreshSessionFromDB(event, session.id);
        }
    });
    sessionHooks.hook('clear', async (session, event) => {
        if(session.id && session.user)
        {
            try
            {
                db.delete(userSessionsTable).where(and(eq(userSessionsTable.id, sql.placeholder('id')), eq(userSessionsTable.user_id, sql.placeholder('user_id')))).prepare().run({ id: session.id, user_id: session.user.id });
            }
            catch(e) { }
        }
    });
});