"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { getTypedSession } from "../auth.js";
import { UserService } from "../services/user.service.js";
async function updateProfile(data) {
  var _a;
  try {
    const headersList = await headers();
    const session = await getTypedSession(headersList);
    if (!((_a = session == null ? void 0 : session.user) == null ? void 0 : _a.id)) {
      return { success: false, error: "Authentication required" };
    }
    const userId = session.user.id;
    if (!data || Object.keys(data).length === 0) {
      return { success: false, error: "No fields provided for update" };
    }
    const updatePayload = {};
    if (data.firstName !== void 0) updatePayload.firstName = data.firstName;
    if (data.lastName !== void 0) updatePayload.lastName = data.lastName;
    if (data.name !== void 0) updatePayload.name = data.name;
    if (data.country !== void 0) updatePayload.country = data.country;
    if (data.timezone !== void 0) updatePayload.timezone = data.timezone;
    if (data.language !== void 0) updatePayload.language = data.language;
    if (Object.keys(updatePayload).length === 0) {
      return { success: false, error: "No valid fields provided for update" };
    }
    const updatedUser = await UserService.updateUser(userId, updatePayload, userId);
    revalidatePath("/dashboard/settings");
    revalidatePath("/dashboard/settings/profile");
    return {
      success: true,
      data: {
        id: updatedUser.id,
        email: updatedUser.email,
        name: updatedUser.name ?? void 0,
        firstName: updatedUser.firstName ?? void 0,
        lastName: updatedUser.lastName ?? void 0,
        image: updatedUser.image ?? void 0,
        country: updatedUser.country ?? void 0,
        timezone: updatedUser.timezone ?? void 0,
        language: updatedUser.language ?? void 0
      }
    };
  } catch (error) {
    console.error("[updateProfile] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to update profile"
    };
  }
}
async function updateAvatar(formData) {
  var _a;
  try {
    const headersList = await headers();
    const session = await getTypedSession(headersList);
    if (!((_a = session == null ? void 0 : session.user) == null ? void 0 : _a.id)) {
      return { success: false, error: "Authentication required" };
    }
    const userId = session.user.id;
    const avatarValue = formData.get("avatar") ?? formData.get("image");
    if (!avatarValue) {
      return { success: false, error: "Avatar image is required" };
    }
    let imageUrl;
    if (typeof avatarValue === "string") {
      imageUrl = avatarValue;
    } else {
      return {
        success: false,
        error: "Please upload the image first and pass the URL"
      };
    }
    if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://") && !imageUrl.startsWith("/")) {
      return { success: false, error: "Invalid image URL format" };
    }
    const updatedUser = await UserService.updateUser(
      userId,
      { image: imageUrl },
      userId
    );
    revalidatePath("/dashboard/settings");
    revalidatePath("/dashboard/settings/profile");
    revalidatePath("/dashboard");
    return {
      success: true,
      data: {
        id: updatedUser.id,
        email: updatedUser.email,
        name: updatedUser.name ?? void 0,
        firstName: updatedUser.firstName ?? void 0,
        lastName: updatedUser.lastName ?? void 0,
        image: updatedUser.image ?? void 0,
        country: updatedUser.country ?? void 0,
        timezone: updatedUser.timezone ?? void 0,
        language: updatedUser.language ?? void 0
      }
    };
  } catch (error) {
    console.error("[updateAvatar] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to update avatar"
    };
  }
}
async function deleteAccount() {
  var _a;
  try {
    const headersList = await headers();
    const session = await getTypedSession(headersList);
    if (!((_a = session == null ? void 0 : session.user) == null ? void 0 : _a.id)) {
      return { success: false, error: "Authentication required" };
    }
    const userId = session.user.id;
    const { TeamService } = await import("../services/team.service.js");
    const ownedTeams = await TeamService.getByOwnerId(userId);
    if (ownedTeams.length > 0) {
      return {
        success: false,
        error: "Cannot delete account while owning teams. Transfer ownership or delete teams first."
      };
    }
    await UserService.deleteAllUserMetas(userId, userId);
    const { mutateWithRLS } = await import("../db.js");
    const result = await mutateWithRLS(
      'DELETE FROM "users" WHERE id = $1',
      [userId],
      userId
    );
    if (result.rowCount === 0) {
      return { success: false, error: "User not found" };
    }
    revalidatePath("/");
    return { success: true };
  } catch (error) {
    console.error("[deleteAccount] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to delete account"
    };
  }
}
export {
  deleteAccount,
  updateAvatar,
  updateProfile
};
