import { BaseModel } from '#database/base_model' import { CommandRecord, CommandStatus } from '../domain/commands/command.js' import { ModeType } from '../domain/shared/mode.js' import { ObjectId } from 'mongodb' export default class CommandModel extends BaseModel { static collectionName = 'commands' static async findByDevice(deviceIdentifier: string): Promise { const collection = this.getCollection() return collection.find({ deviceIdentifier }).sort({ createdAt: -1 }).toArray() as unknown as Promise } static async findPending(deviceIdentifier: string, mode?: ModeType): Promise { const filter: any = { deviceIdentifier, status: CommandStatus.PENDING } if (mode) filter.mode = mode const collection = this.getCollection() return collection.find(filter).sort({ priority: 1 }).toArray() as unknown as Promise } static async createCommand(command: Omit): Promise { const collection = this.getCollection() const doc = { ...command, createdAt: new Date(), updatedAt: new Date() } const result = await collection.insertOne(doc) return { ...doc, _id: result.insertedId } as CommandRecord } static async updateCommand(id: ObjectId, update: Partial): Promise { const collection = this.getCollection() await collection.updateOne({ _id: id }, { $set: { ...update, updatedAt: new Date() } }) } static async deleteById(id: string | ObjectId): Promise { const collection = this.getCollection() const objectId = typeof id === 'string' ? new ObjectId(id) : id const result = await collection.deleteOne({ _id: objectId }) return result.deletedCount === 1 } }