import Foundation
import GRDB
import NucleicProtocol

/// Durable mesh-dispatch queue persistence (`MeshDispatchPersisting`) over the `mesh_dispatch`
/// table (v28).
extension GRDBMetadataStore: MeshDispatchPersisting {
    public func enqueueMeshDispatch(_ record: MeshDispatchRecord) async throws {
        try await writer.write { db in
            try db.execute(sql: """
                INSERT OR REPLACE INTO mesh_dispatch
                  (id, project_id, message, model, effort, auto, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                """, arguments: [
                    record.id, record.projectID.rawValue, record.message,
                    record.model, record.effort, record.auto, record.createdAt,
                ])
        }
    }

    public func queuedMeshDispatches() async throws -> [MeshDispatchRecord] {
        try await writer.read { db in
            try Row.fetchAll(db, sql: "SELECT * FROM mesh_dispatch ORDER BY created_at ASC").map {
                MeshDispatchRecord(
                    id: $0["id"], projectID: ProjectID(rawValue: $0["project_id"]),
                    message: $0["message"], model: $0["model"], effort: $0["effort"],
                    auto: $0["auto"], createdAt: $0["created_at"])
            }
        }
    }

    public func removeMeshDispatch(id: String) async throws {
        try await writer.write { db in
            try db.execute(sql: "DELETE FROM mesh_dispatch WHERE id = ?", arguments: [id])
        }
    }

    public func removeMeshDispatches(projectID: ProjectID) async throws {
        try await writer.write { db in
            try db.execute(
                sql: "DELETE FROM mesh_dispatch WHERE project_id = ?",
                arguments: [projectID.rawValue])
        }
    }
}
