"use server";
import { revalidatePath } from "next/cache";
import { headers } from "next/headers";
import { getTypedSession } from "../auth.js";
import { TeamService } from "../services/team.service.js";
import { TeamMemberService } from "../services/team-member.service.js";
async function getAuthUser() {
  var _a;
  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" };
  }
  return { success: true, userId: session.user.id };
}
async function verifyTeamPermission(userId, teamId, requiredRoles = ["owner", "admin"]) {
  const hasPermission = await TeamMemberService.hasPermission(
    userId,
    teamId,
    requiredRoles
  );
  if (!hasPermission) {
    return { success: false, error: "Permission denied. Required role: " + requiredRoles.join(" or ") };
  }
  return { success: true };
}
async function updateTeam(teamId, data) {
  try {
    if (!(teamId == null ? void 0 : teamId.trim())) {
      return { success: false, error: "Team ID is required" };
    }
    if (!data || Object.keys(data).length === 0) {
      return { success: false, error: "No fields provided for update" };
    }
    const authResult = await getAuthUser();
    if (!authResult.success) {
      return { success: false, error: authResult.error };
    }
    const { userId } = authResult;
    const permResult = await verifyTeamPermission(userId, teamId, ["owner", "admin"]);
    if (!permResult.success) {
      return { success: false, error: permResult.error };
    }
    const updatePayload = {};
    if (data.name !== void 0) updatePayload.name = data.name;
    if (data.slug !== void 0) updatePayload.slug = data.slug;
    if (data.description !== void 0) updatePayload.description = data.description;
    if (data.avatarUrl !== void 0) updatePayload.avatarUrl = data.avatarUrl;
    if (data.settings !== void 0) updatePayload.settings = data.settings;
    if (Object.keys(updatePayload).length === 0) {
      return { success: false, error: "No valid fields provided for update" };
    }
    if (updatePayload.slug) {
      const isAvailable = await TeamService.isSlugAvailable(updatePayload.slug, teamId);
      if (!isAvailable) {
        return { success: false, error: "Team slug is already taken" };
      }
    }
    const updatedTeam = await TeamService.update(teamId, updatePayload, userId);
    revalidatePath("/dashboard/settings/team");
    revalidatePath("/dashboard");
    return { success: true, data: updatedTeam };
  } catch (error) {
    console.error("[updateTeam] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to update team"
    };
  }
}
async function inviteMember(teamId, email, role = "member") {
  try {
    if (!(teamId == null ? void 0 : teamId.trim())) {
      return { success: false, error: "Team ID is required" };
    }
    if (!(email == null ? void 0 : email.trim())) {
      return { success: false, error: "Email is required" };
    }
    const validRoles = ["admin", "member", "viewer"];
    if (!validRoles.includes(role)) {
      return { success: false, error: "Invalid role. Must be admin, member, or viewer" };
    }
    const authResult = await getAuthUser();
    if (!authResult.success) {
      return { success: false, error: authResult.error };
    }
    const { userId } = authResult;
    const permResult = await verifyTeamPermission(userId, teamId, ["owner", "admin"]);
    if (!permResult.success) {
      return { success: false, error: permResult.error };
    }
    const { UserService } = await import("../services/user.service.js");
    const targetUser = await UserService.getUserByEmail(email, userId);
    if (!targetUser) {
      return { success: false, error: "User not found. They must create an account first." };
    }
    const existingMember = await TeamMemberService.getByTeamAndUser(teamId, targetUser.id);
    if (existingMember) {
      return { success: false, error: "User is already a member of this team" };
    }
    const member = await TeamMemberService.add(teamId, targetUser.id, role, {
      invitedBy: userId
    });
    revalidatePath("/dashboard/settings/team");
    revalidatePath("/dashboard/settings/team/members");
    return {
      success: true,
      data: {
        memberId: member.id,
        userId: member.userId,
        teamId: member.teamId,
        role: member.role
      }
    };
  } catch (error) {
    console.error("[inviteMember] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to invite member"
    };
  }
}
async function removeMember(teamId, memberId) {
  try {
    if (!(teamId == null ? void 0 : teamId.trim())) {
      return { success: false, error: "Team ID is required" };
    }
    if (!(memberId == null ? void 0 : memberId.trim())) {
      return { success: false, error: "Member ID is required" };
    }
    const authResult = await getAuthUser();
    if (!authResult.success) {
      return { success: false, error: authResult.error };
    }
    const { userId } = authResult;
    const permResult = await verifyTeamPermission(userId, teamId, ["owner", "admin"]);
    if (!permResult.success) {
      return { success: false, error: permResult.error };
    }
    const targetUserId = memberId;
    if (targetUserId === userId) {
      const selfRole = await TeamMemberService.getRole(teamId, userId);
      if (selfRole === "owner") {
        return { success: false, error: "Cannot remove yourself as owner. Transfer ownership first." };
      }
    }
    const targetRole = await TeamMemberService.getRole(teamId, targetUserId);
    if (targetRole === "owner") {
      return { success: false, error: "Cannot remove team owner. Transfer ownership first." };
    }
    const requestorRole = await TeamMemberService.getRole(teamId, userId);
    if (requestorRole === "admin" && targetRole === "admin" && targetUserId !== userId) {
      return { success: false, error: "Admins cannot remove other admins. Only the owner can do that." };
    }
    await TeamMemberService.remove(teamId, targetUserId);
    revalidatePath("/dashboard/settings/team");
    revalidatePath("/dashboard/settings/team/members");
    return { success: true };
  } catch (error) {
    console.error("[removeMember] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to remove member"
    };
  }
}
async function updateMemberRole(teamId, memberId, role) {
  try {
    if (!(teamId == null ? void 0 : teamId.trim())) {
      return { success: false, error: "Team ID is required" };
    }
    if (!(memberId == null ? void 0 : memberId.trim())) {
      return { success: false, error: "Member ID is required" };
    }
    const validRoles = ["admin", "member", "viewer"];
    if (!validRoles.includes(role)) {
      return { success: false, error: "Invalid role. Must be admin, member, or viewer. Use transferOwnership for owner." };
    }
    const authResult = await getAuthUser();
    if (!authResult.success) {
      return { success: false, error: authResult.error };
    }
    const { userId } = authResult;
    const requestorRole = await TeamMemberService.getRole(teamId, userId);
    if (!requestorRole) {
      return { success: false, error: "You are not a member of this team" };
    }
    const targetUserId = memberId;
    const currentRole = await TeamMemberService.getRole(teamId, targetUserId);
    if (!currentRole) {
      return { success: false, error: "Member not found in this team" };
    }
    if (currentRole === "owner") {
      return { success: false, error: "Cannot change owner role. Use transferOwnership instead." };
    }
    if ((role === "admin" || currentRole === "admin") && requestorRole !== "owner") {
      return { success: false, error: "Only the team owner can promote to or demote from admin" };
    }
    if (requestorRole === "admin" && (role === "member" || role === "viewer")) {
    } else if (requestorRole !== "owner" && requestorRole !== "admin") {
      return { success: false, error: "Permission denied. You must be an owner or admin." };
    }
    const updatedMember = await TeamMemberService.updateRole(teamId, targetUserId, role);
    revalidatePath("/dashboard/settings/team");
    revalidatePath("/dashboard/settings/team/members");
    return { success: true, data: updatedMember };
  } catch (error) {
    console.error("[updateMemberRole] Error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Failed to update member role"
    };
  }
}
export {
  inviteMember,
  removeMember,
  updateMemberRole,
  updateTeam
};
