import { WateringSession } from "../db/models/index.js"; import { getConfiguredDevice } from "./devices.js"; export async function startWateringSession({ patchIds }) { if (!patchIds?.length) { throw new Error("patchIds required"); } const device = await getConfiguredDevice(); if (!device) { throw new Error("No device configured — check config.device"); } const session = await WateringSession.create({ deviceId: device._id, patchIds, startedAt: new Date(), endedAt: null, }); return session.toObject(); } export async function endWateringSession(sessionId) { const s = await WateringSession.findById(sessionId); if (!s) throw new Error("Session not found"); if (s.endedAt) return s.toObject(); s.endedAt = new Date(); await s.save(); return s.toObject(); } export async function endActiveWateringForPatches(patchIds) { const active = await WateringSession.find({ endedAt: null, patchIds: { $in: patchIds }, }); const now = new Date(); for (const s of active) { s.endedAt = now; await s.save(); } return active.length; }