"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 ACCOUNT_SETTINGS_KEYS = [
  // General
  "language", "timezone", "dateFormat", "theme", "compactMode", "showWelcomeScreen", "defaultLandingPage",
  // Notifications
  "notifyEmail", "notifyBrowser", "notifyActivity", "notifySecurityAlerts", "notifyProductUpdates",
  // Email
  "messagesPerPage", "defaultReplyMode", "emailSignature", "composeFormat", "readReceipts",
  // Calendar
  "calendarDefaultView", "weekStartsOn", "workingHoursStart", "workingHoursEnd", "defaultReminder", "defaultEventDuration",
];

const CATEGORY_MAP: Record<string, string> = {
  language: "user.general", timezone: "user.general", dateFormat: "user.general",
  theme: "user.general", compactMode: "user.general", showWelcomeScreen: "user.general",
  defaultLandingPage: "user.general",
  notifyEmail: "user.notifications", notifyBrowser: "user.notifications",
  notifyActivity: "user.notifications", notifySecurityAlerts: "user.notifications",
  notifyProductUpdates: "user.notifications",
  messagesPerPage: "user.email", defaultReplyMode: "user.email",
  emailSignature: "user.email", composeFormat: "user.email", readReceipts: "user.email",
  calendarDefaultView: "user.calendar", weekStartsOn: "user.calendar",
  workingHoursStart: "user.calendar", workingHoursEnd: "user.calendar",
  defaultReminder: "user.calendar", defaultEventDuration: "user.calendar",
};

const BOOLEAN_KEYS = new Set([
  "compactMode", "showWelcomeScreen",
  "notifyEmail", "notifyBrowser", "notifyActivity", "notifySecurityAlerts", "notifyProductUpdates",
  "readReceipts",
]);

export async function saveAccountSettings(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 = ACCOUNT_SETTINGS_KEYS
      .filter((key) => data[key] !== undefined)
      .map((key) => ({
        category: CATEGORY_MAP[key],
        key,
        value: BOOLEAN_KEYS.has(key) ? Boolean(data[key]) : data[key],
      }));

    await batchUpsertUserSettings(user.gscUserId, settings);

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