import { prisma as db } from "@repo/db/client";

export const aiSettingsStorage = {
  async getAiSettings(userId: number) {
    return db.aiSettings.findUnique({ where: { userId } });
  },

  async upsertAiSettings(userId: number, apiKey: string, aiEnabled?: boolean) {
    return db.aiSettings.upsert({
      where: { userId },
      update: { apiKey, ...(aiEnabled !== undefined && { aiEnabled }) },
      create: { userId, apiKey, aiEnabled: aiEnabled ?? true },
    });
  },

  async setAiEnabled(userId: number, enabled: boolean): Promise<void> {
    await db.aiSettings.upsert({
      where:  { userId },
      update: { aiEnabled: enabled },
      create: { userId, apiKey: "", aiEnabled: enabled },
    });
  },

  async upsertProviderKey(userId: number, provider: "openAi" | "claudeAi" | "dentalMgmt", key: string): Promise<void> {
    const field = provider === "openAi" ? "openAiKey" : provider === "claudeAi" ? "claudeAiKey" : "dentalMgmtKey";
    await db.aiSettings.upsert({
      where:  { userId },
      update: { [field]: key },
      create: { userId, apiKey: "", [field]: key },
    });
  },

  async setProviderModel(userId: number, provider: "claudeAi" | "openAi" | "googleAi", model: string): Promise<void> {
    const field = provider === "claudeAi" ? "claudeAiModel" : provider === "openAi" ? "openAiModel" : "googleAiModel";
    await db.aiSettings.upsert({
      where:  { userId },
      update: { [field]: model },
      create: { userId, apiKey: "", [field]: model },
    });
  },

  async setProviderEnabled(userId: number, provider: "openAi" | "claudeAi" | "dentalMgmt", enabled: boolean): Promise<void> {
    const field = provider === "openAi" ? "openAiEnabled" : provider === "claudeAi" ? "claudeAiEnabled" : "dentalMgmtEnabled";
    await db.aiSettings.upsert({
      where:  { userId },
      update: { [field]: enabled },
      create: { userId, apiKey: "", [field]: enabled, openAiEnabled: false, claudeAiEnabled: false, dentalMgmtEnabled: false },
    });
  },

  async getOpenPhoneReply(userId: number): Promise<boolean> {
    const row = await db.aiSettings.findUnique({ where: { userId } });
    return row?.openPhoneReply ?? false;
  },

  async setOpenPhoneReply(userId: number, enabled: boolean): Promise<void> {
    await db.aiSettings.upsert({
      where:  { userId },
      update: { openPhoneReply: enabled },
      create: { userId, apiKey: "", openPhoneReply: enabled },
    });
  },
};
