"use server";

import { revalidatePath } from "next/cache";
import { requireAuth } from "@/auth";
import { batchUpsertUserSettings } from "@/database/settings";

export interface ActionResult {
  success?: boolean;
  message?: string;
  error?: string;
}

const PRIVACY_KEYS = [
  "profileVisibility", "showEmail", "showPhone", "showLocation", "showOnlineStatus",
  "allowDirectMessages", "allowGroupInvites", "allowMentions",
  "allowAnalytics", "allowPersonalization", "allowThirdPartyIntegrations",
  "emailMarketing", "emailProductUpdates", "emailSecurityAlerts", "emailActivityDigest",
  "activityHistoryRetention", "searchHistoryEnabled", "sessionTimeout",
];

const BOOLEAN_KEYS = new Set([
  "showEmail", "showPhone", "showLocation", "showOnlineStatus",
  "allowDirectMessages", "allowGroupInvites", "allowMentions",
  "allowAnalytics", "allowPersonalization", "allowThirdPartyIntegrations",
  "emailMarketing", "emailProductUpdates", "emailSecurityAlerts", "emailActivityDigest",
  "searchHistoryEnabled",
]);

export async function savePrivacySettings(data: Record<string, unknown>): Promise<ActionResult> {
  try {
    const user = await requireAuth();
    if (!user.gscUserId) {
      return { error: "User not linked to database. Please re-login." };
    }

    const settings = PRIVACY_KEYS
      .filter((key) => data[key] !== undefined)
      .map((key) => ({
        category: "user.privacy",
        key,
        value: BOOLEAN_KEYS.has(key)
          ? Boolean(data[key])
          : key === "sessionTimeout"
          ? Number(data[key])
          : data[key],
      }));

    await batchUpsertUserSettings(user.gscUserId, settings);

    revalidatePath("/privacy");
    return { success: true, message: "Privacy settings saved successfully." };
  } catch (error) {
    console.error("[privacy] Save error:", error);
    return { error: "Failed to save privacy settings." };
  }
}
