'use server';

import mongoose from 'mongoose';

import { seedDb } from './seedDb';

declare global {
    var mongoose: any;
}

const MONGO_URL = process.env.MONGO_URL || 'mongodb://mongo:27017/bopeep';

if (!MONGO_URL) {
    throw new Error(
        "Please define the MONGO_URL environment variable inside .env.local",
    );
}

let cached = global.mongoose;

if (!cached) {
    cached = global.mongoose = { conn: null, promise: null };
}

async function connection() {
    if (cached.conn) {
        return cached.conn;
    }

    if (!cached.promise) {
        const opts = {
            bufferCommands: false,
        };

        cached.promise = mongoose.connect(MONGO_URL, opts);
    }
    
    try {
        cached.conn = await cached.promise;
        console.log('Connected to Mongo DB');
    } catch (error) {
        cached.promise = null;
        console.error('Could not connect to Mongo DB', error);
    }

    await seedDb()
        .then(() => console.log('Database seeded'))
        .catch((error) => console.error('Error seeding database', error));

    return cached.conn;
}

export default connection;
