import { eq } from 'drizzle-orm';
import { db } from '../db';
import { dockConfigs, userSettings, userState } from './schema';

// ── User Settings ──

export async function getUserSettings(userId: number): Promise<Record<string, unknown>> {
  const [row] = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
  return (row?.settings as Record<string, unknown>) ?? {};
}

export async function setUserSettings(userId: number, settings: Record<string, unknown>): Promise<void> {
  await db
    .insert(userSettings)
    .values({ userId, settings, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: userSettings.userId,
      set: { settings, updatedAt: new Date() },
    });
}

// ── User State ──

export async function getUserState(userId: number): Promise<Record<string, unknown>> {
  const [row] = await db.select().from(userState).where(eq(userState.userId, userId));
  return (row?.state as Record<string, unknown>) ?? {};
}

export async function patchUserState(userId: number, patch: Record<string, unknown>): Promise<Record<string, unknown>> {
  const current = await getUserState(userId);
  const merged = { ...current, ...patch };
  await db
    .insert(userState)
    .values({ userId, state: merged, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: userState.userId,
      set: { state: merged, updatedAt: new Date() },
    });
  return merged;
}

// ── Dock Config ──

export async function getDockPaths(userId: number): Promise<string[] | null> {
  const [row] = await db.select().from(dockConfigs).where(eq(dockConfigs.userId, userId));
  return (row?.paths as string[]) ?? null;
}

export async function setDockPaths(userId: number, paths: string[]): Promise<void> {
  await db
    .insert(dockConfigs)
    .values({ userId, paths, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: dockConfigs.userId,
      set: { paths, updatedAt: new Date() },
    });
}
