module.exports = async function generateInvoiceNumber(db) {
    const year = new Date().getFullYear();

    const [rows] = await db.promise().query(
        "SELECT counter FROM invoice_counters WHERE year = ?",
        [year]
    );

    let counter = 1;

    if (rows.length === 0) {
        await db.promise().query(
            "INSERT INTO invoice_counters (year, counter) VALUES (?, 1)",
            [year]
        );
    } else {
        counter = rows[0].counter + 1;
        await db.promise().query(
            "UPDATE invoice_counters SET counter = ? WHERE year = ?",
            [counter, year]
        );
    }

    return `R-${year}-${String(counter).padStart(5, "0")}`;
};
