"use server";

import { revalidatePath } from "next/cache";
import {
  upsertFollowMe,
  updateExtension,
  updateVoicemailBox,
} from "@/database/pbx";

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

export async function updateUserCallForwarding(formData: FormData): Promise<ActionResult> {
  const extensionId = formData.get("extensionId") as string;
  const forwardingEnabled = formData.has("forwardingEnabled");
  const ringTime = formData.get("ringTime") as string;

  if (!extensionId) {
    return { error: "Extension ID is required" };
  }

  try {
    const numbers: Array<{ number: string; ringDelay: number; orderNum: number }> = [];
    let idx = 0;
    while (formData.has(`forwardNumber_${idx}`)) {
      const number = formData.get(`forwardNumber_${idx}`) as string;
      if (number && number.trim()) {
        numbers.push({ number: number.trim(), ringDelay: 0, orderNum: idx + 1 });
      }
      idx++;
    }

    await upsertFollowMe(extensionId, {
      isEnabled: forwardingEnabled,
      ringTime: ringTime ? parseInt(ringTime) : 20,
      numbers,
    });

    revalidatePath("/voice");
    return { success: true, message: "Call forwarding settings updated" };
  } catch (error) {
    console.error("Error updating call forwarding:", error);
    return { error: "Failed to update call forwarding settings" };
  }
}

export async function updateUserMoh(formData: FormData): Promise<ActionResult> {
  const tenantId = formData.get("tenantId") as string;
  const extensionId = formData.get("extensionId") as string;
  const mohClassId = formData.get("mohClassId") as string;

  if (!tenantId || !extensionId) {
    return { error: "Tenant ID and Extension ID are required" };
  }

  try {
    await updateExtension(tenantId, extensionId, {
      mohClassId: mohClassId || null,
    });

    revalidatePath("/voice");
    return { success: true, message: "Music on Hold settings updated" };
  } catch (error) {
    console.error("Error updating MOH:", error);
    return { error: "Failed to update Music on Hold settings" };
  }
}

export async function updateUserVoicemail(formData: FormData): Promise<ActionResult> {
  const tenantId = formData.get("tenantId") as string;
  const voicemailBoxId = formData.get("voicemailBoxId") as string;
  const email = formData.get("email") as string;
  const pin = formData.get("pin") as string;
  const emailNotify = formData.has("emailNotify");
  const attachVoicemail = formData.has("attachVoicemail");

  if (!tenantId || !voicemailBoxId) {
    return { error: "Tenant ID and Voicemail Box ID are required" };
  }

  try {
    const data: Record<string, unknown> = {
      email: email || null,
      emailNotify,
      attachVoicemail,
    };

    if (pin && pin.trim()) {
      data.pin = pin.trim();
    }

    await updateVoicemailBox(tenantId, voicemailBoxId, data as Parameters<typeof updateVoicemailBox>[2]);

    revalidatePath("/voice");
    return { success: true, message: "Voicemail settings updated" };
  } catch (error) {
    console.error("Error updating voicemail:", error);
    return { error: "Failed to update voicemail settings" };
  }
}
