const fs = require('node:fs');
const apiKey = process.env.OMNIVORE_API_KEY;
const cacheFile = '.cache/links.json';

const query = `query Search($after: String, $first: Int, $query: String, $format: String, $includeContent: Boolean) {
    search(after: $after, first: $first, query: $query, format: $format, includeContent: $includeContent) {
        ... on SearchSuccess {
            edges {
                cursor
                node {
                    title
                    slug
                    url
                    createdAt
                    isArchived
                    author
                    image
                    description
                    publishedAt
                    originalArticleUrl
                    labels {
                        id
                        name
                        color
                    }
                    siteName
                    savedAt
                }
            }
            pageInfo {
                hasNextPage
                hasPreviousPage
                startCursor
                endCursor
                totalCount
            }
        }
        ... on SearchError {
            errorCodes
        }
    }
}
`;

const cachedContent = () => {
    if (fs.existsSync(cacheFile)) {
        return JSON.parse(fs.readFileSync(cacheFile));
    }

    return [];
}

const storeCache = (content = []) => {
    fs.writeFileSync(cacheFile, JSON.stringify(content));
}

const fetchLatest = async (cache = []) => {
    const after = cache[0]?.cursor;

    const variables = {
        "query": "label:Tech",
        "first": 100,
        after,
    }

    const results = await fetch('https://api-prod.omnivore.app/api/graphql', {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'authorization': apiKey,
        },
        body: JSON.stringify({
            query,
            variables
        })
    });

    if (results.ok) {
        const {data} = await results.json();
        if (data.search.edges.length) {
            const links = [...data.search.edges, ...cache];
            storeCache(links);
            return links;
        }
    } else {
        console.error(await results.text())
    }

    return cache;
}

module.exports = async function() {
    return await fetchLatest(cachedContent());
}