import pool from "../db";

export async function getAllRanks() {
    const rows = await pool.query(
        'SELECT id, name, short_name, sort_id FROM ranks;'
    );
    return rows;
}

export async function getRankByName(name: string) {
    const rows = await pool.query(`SELECT id, name, short_name, sort_id FROM ranks WHERE name = ?`, [name]);

    if (rows.length === 0)
        throw new Error("Could not find rank: " + name);

    return rows[0];
}

export async function insertMemberRank(member_id: number, rank_id: number, date: Date): Promise<void>;
export async function insertMemberRank(member_id: number, rank_id: number): Promise<void>;

export async function insertMemberRank(member_id: number, rank_id: number, date?: Date): Promise<void> {
    const sql = date
        ? `INSERT INTO members_ranks (member_id, rank_id, start_date) VALUES (?, ?, ?);`
        : `INSERT INTO members_ranks (member_id, rank_id, start_date) VALUES (?, ?, NOW());`;

    const params = date
        ? [member_id, rank_id, date]
        : [member_id, rank_id];

    await pool.query(sql, params);
}
