"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;
}

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

    await batchUpsertUserSettings(user.gscUserId, [
      { category: "user.security", key: "loginNotifications", value: data.loginNotifications },
    ]);

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