// src/repositories/sessions.repo.js
const db = require('../db/knex');

async function listByCharger(charger_id) {
    return db('charger_sessions')
        .where({ charger_id })
        .orderBy('started_at', 'desc');
}

async function findByIdForUser(id, userId) {
    return db('charger_sessions')
        .join('chargers', 'charger_sessions.charger_id', 'chargers.id')
        .where({ 'charger_sessions.id': id, 'chargers.user_id': userId })
        .select('charger_sessions.*')
        .first();
}

async function insertSession(data) {
    const [row] = await db('charger_sessions').insert(data).returning('*');
    return row;
}

async function updateById(id, patch) {
    const [row] = await db('charger_sessions').where({ id }).update(patch).returning('*');
    return row;
}

async function deleteByIdForUser(id, userId) {
    return db('charger_sessions')
        .join('chargers', 'charger_sessions.charger_id', 'chargers.id')
        .where({ 'charger_sessions.id': id, 'chargers.user_id': userId })
        .del();
}

async function historyAgg(chargerId, viewMode) {
    let qb = db('charger_sessions')
        .where({ charger_id: chargerId })
        .sum('kwh as total_kwh');

    switch (viewMode) {
        case 'Day':
            qb = qb
                .select(db.raw('DATE(started_at) AS period'))
                .groupBy(db.raw('DATE(started_at)'))
                .orderBy('period', 'desc');
            break;

        case 'Week':
            qb = qb
                .select(
                    db.raw('EXTRACT(ISOYEAR FROM started_at) AS y'),
                    db.raw('EXTRACT(WEEK FROM started_at) AS w'),
                    db.raw(
                        "EXTRACT(ISOYEAR FROM started_at)||'-'||LPAD(EXTRACT(WEEK FROM started_at)::text,2,'0') AS period"
                    )
                )
                .groupBy('y', 'w')
                .orderBy([{ column: 'y', order: 'desc' }, { column: 'w', order: 'desc' }]);
            break;

        case 'Month':
            qb = qb
                .select(
                    db.raw('EXTRACT(YEAR FROM started_at) AS y'),
                    db.raw('EXTRACT(MONTH FROM started_at) AS m'),
                    db.raw(
                        "EXTRACT(YEAR FROM started_at)||'-'||LPAD(EXTRACT(MONTH FROM started_at)::text,2,'0') AS period"
                    )
                )
                .groupBy('y', 'm')
                .orderBy([{ column: 'y', order: 'desc' }, { column: 'm', order: 'desc' }]);
            break;
    }

    return qb;
}

module.exports = {
    listByCharger,
    findByIdForUser,
    insertSession,
    updateById,
    deleteByIdForUser,
    historyAgg,
};
