import { getPrisma } from "./db";

export type AppSetupData = {
  googleAuthEnabled: boolean;
  googleClientId?: string | null;
  googleClientSecret?: string | null;
  socials?: {
    twitter?: string;
    instagram?: string;
    linkedin?: string;
    youtube?: string;
    [key: string]: string | undefined;
  };
  categories?: string[];
};

const defaultSetup: AppSetupData = {
  googleAuthEnabled: false,
  googleClientId: null,
  googleClientSecret: null,
  socials: {},
  categories: ["Basics", "Planning", "Tax", "Healthcare", "Advanced"],
};

export async function getAppSetup(): Promise<AppSetupData> {
  const prisma = await getPrisma();
  if (!prisma) return defaultSetup;

  const row = await prisma.appSetup.findUnique({ where: { id: 1 } });
  if (!row) return defaultSetup;

  return {
    googleAuthEnabled: row.googleAuthEnabled,
    googleClientId: row.googleClientId,
    googleClientSecret: row.googleClientSecret,
    socials: (row.socials || {}) as any,
    categories: (row.categories || []) as any,
  };
}

export async function saveAppSetup(data: AppSetupData) {
  const prisma = await getPrisma();
  if (!prisma) return defaultSetup;

  const saved = await prisma.appSetup.upsert({
    where: { id: 1 },
    update: {
      googleAuthEnabled: data.googleAuthEnabled,
      googleClientId: data.googleClientId || null,
      googleClientSecret: data.googleClientSecret || null,
      socials: (data.socials || {}) as any,
      categories: (data.categories || []) as any,
    },
    create: {
      id: 1,
      googleAuthEnabled: data.googleAuthEnabled,
      googleClientId: data.googleClientId || null,
      googleClientSecret: data.googleClientSecret || null,
      socials: (data.socials || {}) as any,
      categories: (data.categories || []) as any,
    },
  });

  return {
    googleAuthEnabled: saved.googleAuthEnabled,
    googleClientId: saved.googleClientId,
    googleClientSecret: saved.googleClientSecret,
    socials: (saved.socials || {}) as any,
    categories: (saved.categories || []) as any,
  } as AppSetupData;
}
