import { prisma } from "./prisma";
import { encrypt, decrypt } from "./crypto";
import { env } from "../config/env";

// Clés des réglages stockés en base (AppSetting).
export const CONFIG_KEYS = {
  googleClientId: "google.client_id",
  googleClientSecret: "google.client_secret",
  googleRedirectUri: "google.redirect_uri",
} as const;

// Lit un réglage (déchiffre si secret). Renvoie null si absent.
export async function readSetting(key: string): Promise<string | null> {
  const s = await prisma.appSetting.findUnique({ where: { key } });
  if (!s) return null;
  try {
    return s.isSecret ? decrypt(s.value) : s.value;
  } catch {
    return null;
  }
}

// Écrit/maj un réglage (chiffre si secret). Une valeur vide supprime le réglage.
export async function writeSetting(key: string, value: string, isSecret = false): Promise<void> {
  if (value === "") {
    await prisma.appSetting.deleteMany({ where: { key } });
    return;
  }
  const stored = isSecret ? encrypt(value) : value;
  await prisma.appSetting.upsert({
    where: { key },
    create: { key, value: stored, isSecret },
    update: { value: stored, isSecret },
  });
}

export interface GoogleConfig {
  clientId: string;
  clientSecret: string;
  redirectUri: string;
}

// Config Google effective : la base prime, sinon repli sur le .env.
export async function getGoogleConfig(): Promise<GoogleConfig> {
  const [clientId, clientSecret, redirectUri] = await Promise.all([
    readSetting(CONFIG_KEYS.googleClientId),
    readSetting(CONFIG_KEYS.googleClientSecret),
    readSetting(CONFIG_KEYS.googleRedirectUri),
  ]);
  return {
    clientId: clientId ?? env.google.clientId,
    clientSecret: clientSecret ?? env.google.clientSecret,
    redirectUri: redirectUri || env.google.redirectUri,
  };
}
