import Agenda, { Job } from "agenda";
import fs from "fs";
import path from "path";
import { PaymentService } from "../api/services/payment.service";
const paymentService = new PaymentService();

const mongoUrl = process.env[`MONGODB_${(process.env.APPLICATION_ENV || 'LOCAL').toUpperCase()}`] || process.env.MONGODB || "mongodb://localhost:27017/myseatime";
const agenda = new Agenda({
    db: { address: mongoUrl, collection: "agenda" },
});

// Load all jobs from directory
const jobsDir = path.join(__dirname, "../jobs");
export const loadJobs = async () => {
    fs.readdirSync(jobsDir).forEach(async (file) => {
        if (file.endsWith(".ts") || file.endsWith(".js")) {
            const jobPath = path.join(jobsDir, file);
            const registerJob = (await import(jobPath)).default;
            if (typeof registerJob === "function") {
                registerJob(agenda);
                console.log(`✅ Loaded job: ${file}`);
            }
        }
    });
};

export const createJobs = async(date: Date, description: string, args: any) => {
    if(args.type === "expiry-gift-card-subscription") {
        agenda.define(description, async (job: Job) => {
            const { subscriptionId } = job.attrs.data;
            const expireSubscriptionInput: any = { subscriptionId };
            await paymentService.expireSubscription(expireSubscriptionInput);
            console.log(`✅ Premium subscription expired for: ${subscriptionId}`);
        });
        await agenda.schedule(date, description, args);
    }
}

export const executeJob=async(jobName:string)=>{
    const jobs = await agenda.jobs({ name: jobName });
    if(jobs.length){
        jobs[0].run();
        return true;
    }else{
        return false;
    }
}

export default agenda;
