import { organizations, instanceSettings } from "@rudderhq/db";
import { instanceGeneralSettingsSchema, instanceNotificationSettingsSchema, } from "@rudderhq/shared";
import { eq } from "drizzle-orm";
const DEFAULT_SINGLETON_KEY = "default";
function stripLegacyGitIdentity(raw) {
    if (!raw || typeof raw !== "object" || Array.isArray(raw))
        return raw;
    const { gitIdentity: _gitIdentity, ...rest } = raw;
    return rest;
}
function normalizeGeneralSettings(raw) {
    const parsed = instanceGeneralSettingsSchema.safeParse(stripLegacyGitIdentity(raw) ?? {});
    if (parsed.success) {
        return {
            censorUsernameInLogs: parsed.data.censorUsernameInLogs ?? false,
            showDeveloperDiagnostics: parsed.data.showDeveloperDiagnostics ?? false,
            locale: parsed.data.locale ?? "en",
        };
    }
    return {
        censorUsernameInLogs: false,
        showDeveloperDiagnostics: false,
        locale: "en",
    };
}
export function normalizeInstanceLocale(raw) {
    return normalizeGeneralSettings({ locale: raw }).locale;
}
function normalizeNotificationSettings(raw) {
    const parsed = instanceNotificationSettingsSchema.safeParse(raw ?? {});
    if (parsed.success) {
        const desktopIssueNotifications = parsed.data.desktopIssueNotifications ?? parsed.data.desktopInboxNotifications ?? true;
        return {
            desktopInboxNotifications: desktopIssueNotifications,
            desktopDockBadge: parsed.data.desktopDockBadge ?? true,
            desktopIssueNotifications,
            desktopChatNotifications: parsed.data.desktopChatNotifications ?? true,
        };
    }
    return {
        desktopInboxNotifications: true,
        desktopDockBadge: true,
        desktopIssueNotifications: true,
        desktopChatNotifications: true,
    };
}
function toInstanceSettings(row) {
    return {
        id: row.id,
        general: normalizeGeneralSettings(row.general),
        notifications: normalizeNotificationSettings(row.notifications),
        createdAt: row.createdAt,
        updatedAt: row.updatedAt,
    };
}
export function instanceSettingsService(db) {
    async function getOrCreateRow() {
        const existing = await db
            .select()
            .from(instanceSettings)
            .where(eq(instanceSettings.singletonKey, DEFAULT_SINGLETON_KEY))
            .then((rows) => rows[0] ?? null);
        if (existing)
            return existing;
        const now = new Date();
        const [created] = await db
            .insert(instanceSettings)
            .values({
            singletonKey: DEFAULT_SINGLETON_KEY,
            general: {},
            notifications: {},
            createdAt: now,
            updatedAt: now,
        })
            .onConflictDoUpdate({
            target: [instanceSettings.singletonKey],
            set: {
                updatedAt: now,
            },
        })
            .returning();
        return created;
    }
    async function updateGeneralJson(patch) {
        const current = await getOrCreateRow();
        const nextGeneral = normalizeGeneralSettings({
            ...normalizeGeneralSettings(current.general),
            ...patch,
        });
        const now = new Date();
        const [updated] = await db
            .update(instanceSettings)
            .set({
            general: { ...nextGeneral },
            updatedAt: now,
        })
            .where(eq(instanceSettings.id, current.id))
            .returning();
        return toInstanceSettings(updated ?? current);
    }
    return {
        get: async () => toInstanceSettings(await getOrCreateRow()),
        getGeneral: async () => {
            const row = await getOrCreateRow();
            return normalizeGeneralSettings(row.general);
        },
        getNotifications: async () => {
            const row = await getOrCreateRow();
            return normalizeNotificationSettings(row.notifications);
        },
        updateGeneral: async (patch) => {
            return updateGeneralJson(patch);
        },
        updateNotifications: async (patch) => {
            const current = await getOrCreateRow();
            const nextNotifications = normalizeNotificationSettings({
                ...normalizeNotificationSettings(current.notifications),
                ...patch,
            });
            if (patch.desktopIssueNotifications != null) {
                nextNotifications.desktopInboxNotifications = nextNotifications.desktopIssueNotifications;
            }
            else if (patch.desktopInboxNotifications != null) {
                nextNotifications.desktopIssueNotifications = nextNotifications.desktopInboxNotifications;
            }
            if ((patch.desktopInboxNotifications === true || patch.desktopIssueNotifications === true)
                && patch.desktopDockBadge == null) {
                nextNotifications.desktopDockBadge = true;
            }
            const now = new Date();
            const [updated] = await db
                .update(instanceSettings)
                .set({
                notifications: { ...nextNotifications },
                updatedAt: now,
            })
                .where(eq(instanceSettings.id, current.id))
                .returning();
            return toInstanceSettings(updated ?? current);
        },
        listCompanyIds: async () => db
            .select({ id: organizations.id })
            .from(organizations)
            .then((rows) => rows.map((row) => row.id)),
    };
}
//# sourceMappingURL=instance-settings.js.map