import { v } from "convex/values";

import { mutation, query } from "./_generated/server";

const now = () => Date.now();

export const upsert = mutation({
  args: {
    daemonId: v.string(),
    name: v.string(),
    desiredState: v.union(v.literal("online"), v.literal("offline")),
    agentOsConfig: v.any(),
  },
  handler: async (ctx, args) => {
    const existing = await ctx.db
      .query("daemonDefinitions")
      .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId))
      .unique();
    const timestamp = now();
    if (existing) {
      await ctx.db.patch("daemonDefinitions", existing._id, {
        name: args.name,
        desiredState: args.desiredState,
        agentOsConfig: args.agentOsConfig,
        configVersion: existing.configVersion + 1,
        updatedAt: timestamp,
      });
      return existing._id;
    }
    return await ctx.db.insert("daemonDefinitions", {
      ...args,
      configVersion: 1,
      createdAt: timestamp,
      updatedAt: timestamp,
    });
  },
});

export const get = query({
  args: { daemonId: v.string() },
  handler: async (ctx, args) => {
    const definition = await ctx.db
      .query("daemonDefinitions")
      .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId))
      .unique();
    const presence = await ctx.db
      .query("daemonPresence")
      .withIndex("by_daemonId", (q) => q.eq("daemonId", args.daemonId))
      .order("desc")
      .first();
    return { definition, presence };
  },
});

export const list = query({
  args: {},
  handler: async (ctx) => {
    return await ctx.db.query("daemonDefinitions").order("desc").collect();
  },
});
