#!/usr/bin/env node
/**
 * mailsend CLI — queue and send email from the command line.
 *
 * Usage:
 *   mailsend --to user@example.com --subject "Hello" --body "Message text"
 *   mailsend -q gmail --to user@example.com --subject "Test"
 *   mailsend --status
 *   mailsend --process
 */

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

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

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

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

// Load config
const configPath = getArg("config") || "mailsend.json";
if (!fs.existsSync(configPath)) {
    console.error(`Config file not found: ${configPath}`);
    console.error(`Create a mailsend.json with baseDir, accounts, etc.`);
    process.exit(1);
}

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

if (hasFlag("status")) {
    const status = sender.getStatus();
    for (const [id, s] of Object.entries(status)) {
        console.log(`  ${id}: ${s.pending} pending, ${s.failed} failed`);
    }
    process.exit(0);
}

if (hasFlag("process")) {
    await sender.processAllQueues();
    process.exit(0);
}

const to = getArg("to");
const subject = getArg("subject") || "(no subject)";
const body = getArg("body") || "";
const from = getArg("from") || "";
const accountId = getArg("queue") || config.defaultAccount || "";

if (!to) {
    console.error("Usage: mailsend --to addr [--subject text] [--body text] [--from addr] [-q account]");
    console.error("       mailsend --status");
    console.error("       mailsend --process");
    process.exit(1);
}

const acct = config.accounts[accountId];
if (!acct) {
    console.error(`Unknown account: ${accountId}`);
    console.error(`Available: ${Object.keys(config.accounts).join(", ")}`);
    process.exit(1);
}

const filename = queueMessage({
    from: from || acct.from || acct.user,
    to: to.split(",").map(s => s.trim()),
    subject,
    text: body,
    accountId,
});

console.log(`Queued: ${filename}`);
setTimeout(() => process.exit(0), 2000);
