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

async function listByUser(userId) {
    return db('chargers').where({ user_id: userId }).select('*');
}

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

async function findByMqttTopic(mqtt_topic) {
    return db('chargers').where({ mqtt_topic }).first();
}

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

async function updateChargerForUser(id, userId, patch) {
    const [row] = await db('chargers')
        .where({ id, user_id: userId })
        .update(patch)
        .returning('*');
    return row;
}

async function deleteChargerForUser(id, userId) {
    // devolve o charger antes para poderes usar mqtt_user/pass/topic etc
    const charger = await findByIdForUser(id, userId);
    if (!charger) return null;

    await db('chargers').where({ id, user_id: userId }).del();
    return charger;
}

async function getConfig(charger_id) {
    return db('charger_configs').where({ charger_id }).first();
}

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

async function updateConfig(charger_id, patch) {
    const [row] = await db('charger_configs')
        .where({ charger_id })
        .update(patch)
        .returning('*');
    return row;
}

async function upsertConfig(charger_id, patch) {
    const existing = await getConfig(charger_id);
    if (existing) return updateConfig(charger_id, patch);
    return insertConfig({ charger_id, ...patch });
}

async function listSchedules(charger_id) {
    return db('charger_schedules').where({ charger_id }).orderBy('created_at', 'desc');
}

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

module.exports = {
    listByUser,
    findByIdForUser,
    findByMqttTopic,
    insertCharger,
    updateChargerForUser,
    deleteChargerForUser,
    getConfig,
    insertConfig,
    updateConfig,
    upsertConfig,
    listSchedules,
    insertSchedule,
};
