"use server";
import { db } from "@/lib/db";
import { user } from "@/db/schema";
import { eq } from "drizzle-orm";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import bcrypt from "bcryptjs";
import { revalidatePath } from "next/cache";

export async function actualizarPerfil(formData: FormData) {
  try {
    const session = await getServerSession(authOptions);
    if (!session || !session.user.id) {
      return { success: false, error: "No autorizado." };
    }

    const userId = session.user.id;
    const name = formData.get("name") as string;
    const apellido = formData.get("apellido") as string;
    const cedula = formData.get("cedula") as string;
    const email = formData.get("email") as string;
    const telefono = formData.get("telefono") as string;
    const direccion = formData.get("direccion") as string;
    const password = formData.get("password") as string;

    const dataToUpdate: any = {
      name,
      apellido,
      cedula,
      email: email.toLowerCase(),
      telefono,
      direccion,
      updatedAt: new Date()
    };

    if (password && password.length >= 6) {
      dataToUpdate.password = await bcrypt.hash(password, 10);
    }

    // Verificar si el correo ya existe en otro usuario
    const existingUser = await db.query.user.findFirst({
      where: eq(user.email, email.toLowerCase())
    });

    if (existingUser && existingUser.id !== userId) {
      return { success: false, error: "El correo electrónico ya está en uso por otra cuenta." };
    }

    await db.update(user)
      .set(dataToUpdate)
      .where(eq(user.id, userId));

    revalidatePath("/perfil");
    return { success: true };
  } catch (error: any) {
    console.error("Error al actualizar perfil:", error);
    return { success: false, error: "Ocurrió un error en el servidor." };
  }
}
