import { eq } from 'drizzle-orm';
import { db } from '../db';
import { pluginInstalls } from './schema';

export type PluginInstall = typeof pluginInstalls.$inferSelect;

/** Every installed plugin, oldest first so the list is stable across renders. */
export async function listPluginInstalls(): Promise<PluginInstall[]> {
  return db.select().from(pluginInstalls).orderBy(pluginInstalls.appName);
}

export async function getPluginInstall(appName: string): Promise<PluginInstall | null> {
  const [row] = await db.select().from(pluginInstalls).where(eq(pluginInstalls.appName, appName)).limit(1);
  return row ?? null;
}

/**
 * Record an install, or update the version of one already there.
 *
 * Upsert rather than insert, because re-installing is how a plugin is upgraded: the code on disk moved,
 * and the row should follow it rather than refuse. `enabled` is deliberately NOT touched on the update
 * path — re-installing a plugin the owner had disabled must not silently switch it back on.
 */
export async function recordPluginInstall(appName: string, version: string): Promise<PluginInstall> {
  const [row] = await db
    .insert(pluginInstalls)
    .values({ appName, version })
    .onConflictDoUpdate({
      target: pluginInstalls.appName,
      set: { version, updatedAt: new Date() },
    })
    .returning();
  return row!;
}

export async function setPluginEnabled(appName: string, enabled: boolean): Promise<PluginInstall | null> {
  const [row] = await db
    .update(pluginInstalls)
    .set({ enabled, updatedAt: new Date() })
    .where(eq(pluginInstalls.appName, appName))
    .returning();
  return row ?? null;
}

/** Forget the install. Drops no tables and deletes no data — see the note in schema.ts. */
export async function removePluginInstall(appName: string): Promise<boolean> {
  const rows = await db.delete(pluginInstalls).where(eq(pluginInstalls.appName, appName)).returning();
  return rows.length > 0;
}
