import type { PageServerLoad } from "./$types";

import sqlite3 from "sqlite3";
import { open } from "sqlite";
import type { ICommit } from "$lib/types";

import fs from "fs"

const path = "/tmp/db.sqlite"

export const load: PageServerLoad = async () => {
    //check if db exists
    // const exists = await file.exists()
    if (!fs.existsSync(path)) {
        console.log(`${path} does not exist`)
        return {}
    }
    console.log(`${path} does exist`)
    const fetchCommitDB = async(): Promise<ICommit[]> => open({
        filename: path, // temp location, move to env setting
        driver: sqlite3.Database
    }).then(async (db) => {
        const data: ICommit[] = await db.all(`SELECT * FROM commits ORDER BY date DESC LIMIT 5;`);
        return data;
    })

    return {
        commits: await fetchCommitDB(),
    }

}