import { lt } from "drizzle-orm";
import { emailValidationTable } from "~/db/schema";
import useDatabase from '~/composables/useDatabase';

interface ValidationPayload
{
    type: 'validation'
    id: string
    timestamp: number
}

export default defineTask({
    meta: {
        name: 'validation',
        description: 'Add email ID to DB',
    },
    async run(e) {
        try {
            if(e.payload.type !== 'validation')
            {
                throw new Error(`Données inconnues`);
            }

            const payload = e.payload as ValidationPayload;
            const db = useDatabase();

            db.delete(emailValidationTable).where(lt(emailValidationTable.timestamp, new Date())).run();
            db.insert(emailValidationTable).values({ id: payload.id, timestamp: new Date(payload.timestamp) }).run();
            
            return { result: true };
        }
        catch(e)
        {
            console.error(e);

            return { result: false, error: e };
        }
    },
})