#!/usr/bin/env node
/**
 * mailq — manage the outgoing mail queue.
 *
 * Usage:
 *   mailq                    Show queue status (all accounts)
 *   mailq --process          Process all queues now (send pending, retry failed)
 *   mailq --process -q gmail Process only the gmail queue
 */

import * as fs from "node:fs";
import { initMailSend, type MailSendConfig } from "./index.js";

const args = process.argv.slice(2);

function getArg(name: string): string | undefined {
    const shorts: Record<string, string> = { q: "queue" };
    const longIdx = args.indexOf(`--${name}`);
    const shortKey = Object.entries(shorts).find(([, v]) => v === name)?.[0];
    const shortIdx = shortKey ? args.indexOf(`-${shortKey}`) : -1;
    const i = Math.max(longIdx, shortIdx);
    if (i === -1 || i + 1 >= args.length) return undefined;
    return args[i + 1];
}

function hasFlag(name: string): boolean {
    return args.includes(`--${name}`);
}

const configPath = getArg("config") || "mailsend.json";
if (!fs.existsSync(configPath)) {
    console.error(`Config file not found: ${configPath}`);
    process.exit(1);
}

const config: MailSendConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
const sender = initMailSend(config);

if (hasFlag("process")) {
    const accountId = getArg("queue");
    if (accountId) {
        await sender.processQueue(accountId);
    } else {
        await sender.processAllQueues();
    }
    // Show status after processing
    const status = sender.getStatus();
    for (const [id, s] of Object.entries(status)) {
        console.log(`  ${id}: ${s.pending} pending, ${s.failed} failed`);
    }
} else {
    // Default: show status
    const status = sender.getStatus();
    let total = 0;
    for (const [id, s] of Object.entries(status)) {
        console.log(`  ${id}: ${s.pending} pending, ${s.failed} failed`);
        total += s.pending + s.failed;
    }
    if (total === 0) console.log("  All queues empty");
}

process.exit(0);
