const Database = require('better-sqlite3');
const db = new Database('plusfit.db');

function generateVertragsnummer() {
    const year = new Date().getFullYear();

    // Letzte Vertragsnummer dieses Jahres holen
    const row = db.prepare(`
        SELECT vertragsnummer
        FROM users
        WHERE vertragsnummer LIKE ?
        ORDER BY vertragsnummer DESC
        LIMIT 1
    `).get(`PF-${year}-%`);

    let nextNumber = 1;

    if (row && row.vertragsnummer) {
        const parts = row.vertragsnummer.split('-');
        const lastNumber = parseInt(parts[2], 10);
        nextNumber = lastNumber + 1;
    }

    const padded = String(nextNumber).padStart(6, '0');
    return `PF-${year}-${padded}`;
}

module.exports = generateVertragsnummer;
