import { prisma } from '@/db';
import { Audit, Notification, Setting } from '@/generated/prisma/client';
import { sendToUser } from '@/lib/notification';

type AdminSettingValue = Pick<Setting, 'id' | 'key' | 'value'>;

type AdminSettingValueOnly = {
  [key: string]: string;
};

type AdminSettingFull = {
  [key: string]: AdminSettingValue;
};

export async function getAllAdminSettings(
  valueOnly: true,
): Promise<AdminSettingValueOnly>;

export async function getAllAdminSettings(
  valueOnly?: false,
): Promise<AdminSettingFull>;

export async function getAllAdminSettings(valueOnly = false) {
  const settings = await prisma.setting.findMany({
    where: {
      relation: 'admin',
    },
    select: {
      id: true,
      key: true,
      value: true,
    },
  });

  const results: Record<string, string | AdminSettingValue> = {};

  settings.forEach((setting) => {
    results[setting.key] = valueOnly ? setting.value : setting;
  });

  return results;
}

export const createAuditLog = async (data: Omit<Audit, 'id' | 'createdAt'>) => {
  await prisma.audit.create({
    data: {
      ...data,
    },
  });
};

export const getInitialOrganization = async (userId: string) => {
  const organization = await prisma.house.findFirst({
    where: {
      members: {
        some: {
          userId,
        },
      },
    },
  });

  return organization;
};

export const createNotification = async (
  data: Omit<Notification, 'id' | 'createdAt'>,
) => {
  await prisma.notification.create({
    data: {
      ...data,
    },
  });

  sendToUser(data.userId, {
    type: 'NEW_NOTIFICATION',
    title: data.title,
    message: data.message,
  });
};
