"use server";

import { z } from "zod";
import { prisma } from "@formbricks/database";
import { OrganizationRole } from "@formbricks/database/prisma";
import { logger } from "@formbricks/logger";
import { ZId, ZUuid } from "@formbricks/types/common";
import { AuthenticationError, OperationNotAllowedError, ValidationError } from "@formbricks/types/errors";
import { TOrganizationRole, ZOrganizationRole } from "@formbricks/types/memberships";
import { ZUserEmail } from "@formbricks/types/user";
import { assertCan, can } from "@/lib/authorization";
import { INVITE_DISABLED, IS_FORMBRICKS_CLOUD } from "@/lib/constants";
import { createInviteToken } from "@/lib/jwt";
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
import { assertUserManagementAllowed } from "@/lib/membership/user-management";
import { getAccessFlags } from "@/lib/membership/utils";
import { capturePostHogEvent } from "@/lib/posthog";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { getOrganizationIdFromInviteId } from "@/lib/utils/helper";
import { applyRateLimit } from "@/modules/core/rate-limit/helpers";
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
import { getBulkInvitePermission, getIsMultiOrgEnabled } from "@/modules/ee/license-check/lib/utils";
import {
  assertCanAssignRole,
  checkRoleManagementPermission,
} from "@/modules/ee/role-management/lib/permission";
import { getTeamsWhereUserIsAdmin } from "@/modules/ee/teams/lib/roles";
import { sendInviteMemberEmail } from "@/modules/email";
import {
  deleteMembership,
  getMembershipsByUserId,
} from "@/modules/organization/settings/teams/lib/membership";
import { ZInvitees } from "@/modules/organization/settings/teams/types/invites";
import {
  type TInviteWriteScope,
  deleteInvite,
  getInvite,
  inviteUser,
  refreshInviteExpiration,
  resendInvite,
} from "./lib/invite";
import { type TBulkInviteResult, getInviteFailureReason } from "./lib/invite-failure";
import { reserveInviteRateLimit, settleInviteRateLimit } from "./lib/invite-rate-limit";

// Hard cap on a single bulk import to bound payload size and email fan-out.
const BULK_INVITE_MAX_INVITEES = 500;

// Cap on the teams one invite may name. See ZInviteUserAction.
const INVITE_MAX_TEAMS = 100;

/**
 * What the caller may do to pending invites in this organization: an owner's invite is an owner's to
 * change (ENG-6812), as `deleteMembershipAction` keeps an owner's membership from managers. Read after
 * the authorization checks, so a non-member never reaches it.
 */
const getCallerInviteScope = async (userId: string, organizationId: string): Promise<TInviteWriteScope> => {
  const membership = await getMembershipByUserIdOrganizationId(userId, organizationId);
  if (!membership) {
    throw new AuthenticationError("User not a member of this organization");
  }
  return { allowOwnerInvite: membership.role === "owner" };
};

const ZDeleteInviteAction = z.object({
  inviteId: ZUuid,
});

export const deleteInviteAction = authenticatedActionClient.inputSchema(ZDeleteInviteAction).action(
  withAuditLogging("deleted", "invite", async ({ ctx, parsedInput }) => {
    const organizationId = await getOrganizationIdFromInviteId(parsedInput.inviteId);

    await assertUserManagementAllowed(ctx.user.id, organizationId);
    await assertCan({ type: "user", id: ctx.user.id }, "organization.manage", {
      type: "organization",
      id: organizationId,
    });
    await applyRateLimit(rateLimitConfigs.actions.stateMutation, organizationId);
    ctx.auditLoggingCtx.organizationId = organizationId;
    ctx.auditLoggingCtx.inviteId = parsedInput.inviteId;
    ctx.auditLoggingCtx.oldObject = { ...(await getInvite(parsedInput.inviteId)) };
    return await deleteInvite(parsedInput.inviteId, await getCallerInviteScope(ctx.user.id, organizationId));
  })
);

const ZCreateInviteTokenAction = z.object({
  inviteId: ZUuid,
});

export const createInviteTokenAction = authenticatedActionClient.inputSchema(ZCreateInviteTokenAction).action(
  withAuditLogging("updated", "invite", async ({ parsedInput, ctx }) => {
    const organizationId = await getOrganizationIdFromInviteId(parsedInput.inviteId);

    await assertUserManagementAllowed(ctx.user.id, organizationId);
    await assertCan({ type: "user", id: ctx.user.id }, "organization.manage", {
      type: "organization",
      id: organizationId,
    });
    await applyRateLimit(rateLimitConfigs.actions.stateMutation, organizationId);

    // Get old expiresAt for audit logging before update
    const oldInvite = await prisma.invite.findUnique({
      where: { id: parsedInput.inviteId },
      select: { email: true, expiresAt: true },
    });

    if (!oldInvite) {
      throw new ValidationError("Invite not found");
    }

    // Refresh the invitation expiration
    const updatedInvite = await refreshInviteExpiration(
      parsedInput.inviteId,
      await getCallerInviteScope(ctx.user.id, organizationId)
    );

    // Set audit context
    ctx.auditLoggingCtx.organizationId = organizationId;
    ctx.auditLoggingCtx.inviteId = parsedInput.inviteId;
    ctx.auditLoggingCtx.oldObject = { expiresAt: oldInvite.expiresAt };
    ctx.auditLoggingCtx.newObject = { expiresAt: updatedInvite.expiresAt };

    const inviteToken = createInviteToken(parsedInput.inviteId, updatedInvite.email, {
      expiresIn: "7d",
    });

    return { inviteToken: encodeURIComponent(inviteToken) };
  })
);

const ZDeleteMembershipAction = z.object({
  userId: ZId,
  organizationId: ZId,
});

export const deleteMembershipAction = authenticatedActionClient.inputSchema(ZDeleteMembershipAction).action(
  withAuditLogging("deleted", "membership", async ({ ctx, parsedInput }) => {
    await assertUserManagementAllowed(ctx.user.id, parsedInput.organizationId);
    await assertCan({ type: "user", id: ctx.user.id }, "organization.manage", {
      type: "organization",
      id: parsedInput.organizationId,
    });
    await applyRateLimit(rateLimitConfigs.actions.stateMutation, parsedInput.organizationId);

    if (parsedInput.userId === ctx.user.id) {
      throw new OperationNotAllowedError("You cannot delete yourself from the organization");
    }

    const currentMembership = await getMembershipByUserIdOrganizationId(
      ctx.user.id,
      parsedInput.organizationId
    );

    if (!currentMembership) {
      throw new AuthenticationError("Not a member of this organization");
    }

    const membership = await getMembershipByUserIdOrganizationId(
      parsedInput.userId,
      parsedInput.organizationId
    );

    if (!membership) {
      throw new AuthenticationError("Not a member of this organization");
    }

    const isOwner = membership.role === "owner";

    if (currentMembership.role === "manager" && isOwner) {
      throw new OperationNotAllowedError("You cannot delete the owner of the organization");
    }

    // The last-owner guard runs inside `deleteMembership`'s transaction, where it cannot race.

    ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
    ctx.auditLoggingCtx.membershipId = `${parsedInput.userId}-${parsedInput.organizationId}`;
    ctx.auditLoggingCtx.oldObject = membership;
    return await deleteMembership(parsedInput.userId, parsedInput.organizationId, ctx.user.id);
  })
);

const ZResendInviteAction = z.object({
  inviteId: ZUuid,
  organizationId: ZId,
});

export const resendInviteAction = authenticatedActionClient.inputSchema(ZResendInviteAction).action(
  withAuditLogging("updated", "invite", async ({ ctx, parsedInput }) => {
    if (INVITE_DISABLED) {
      throw new OperationNotAllowedError("Invite are disabled");
    }

    const inviteOrganizationId = await getOrganizationIdFromInviteId(parsedInput.inviteId);

    if (inviteOrganizationId !== parsedInput.organizationId) {
      throw new ValidationError("Invite does not belong to the organization");
    }

    await assertUserManagementAllowed(ctx.user.id, parsedInput.organizationId);
    await assertCan({ type: "user", id: ctx.user.id }, "organization.manage", {
      type: "organization",
      id: parsedInput.organizationId,
    });
    await applyRateLimit(rateLimitConfigs.actions.stateMutation, parsedInput.organizationId);
    const inviteScope = await getCallerInviteScope(ctx.user.id, parsedInput.organizationId);
    const rateLimitReservation = await reserveInviteRateLimit(parsedInput.organizationId, ctx.user.id);

    let invite: Awaited<ReturnType<typeof getInvite>>;
    let updatedInvite: Awaited<ReturnType<typeof resendInvite>>;
    try {
      invite = await getInvite(parsedInput.inviteId);
      updatedInvite = await resendInvite(parsedInput.inviteId, inviteScope);
    } catch (error) {
      await settleInviteRateLimit(rateLimitReservation, 0);
      throw error;
    }
    await settleInviteRateLimit(rateLimitReservation, 1);

    ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
    ctx.auditLoggingCtx.inviteId = parsedInput.inviteId;
    ctx.auditLoggingCtx.oldObject = { ...invite };
    ctx.auditLoggingCtx.newObject = updatedInvite;
    await sendInviteMemberEmail(
      parsedInput.inviteId,
      updatedInvite.email,
      invite?.creator?.name ?? "",
      updatedInvite.name ?? "",
      parsedInput.organizationId,
      ctx.user.id
    );

    return updatedInvite;
  })
);

const validateTeamAdminInvitePermissions = (
  inviterRole: TOrganizationRole,
  inviterAdminTeams: string[],
  inviteRole: TOrganizationRole,
  inviteTeamIds: string[]
): void => {
  const isOrgOwnerOrManager = inviterRole === "owner" || inviterRole === "manager";
  const isTeamAdmin = inviterAdminTeams.length > 0;

  if (!isOrgOwnerOrManager && !isTeamAdmin) {
    throw new AuthenticationError("Only organization owners, managers, or team admins can invite members");
  }

  // Team admins have restrictions
  if (isTeamAdmin && !isOrgOwnerOrManager) {
    if (inviteRole !== "member") {
      throw new OperationNotAllowedError("Team admins can only invite users as members");
    }

    const invalidTeams = inviteTeamIds.filter((id) => !inviterAdminTeams.includes(id));
    if (invalidTeams.length > 0) {
      throw new OperationNotAllowedError("Team admins can only add users to teams where they are admin");
    }

    if (inviteTeamIds.length === 0) {
      throw new ValidationError("Team admins must add invited users to at least one team");
    }
  }
};

/**
 * The capability half of "may this person send this invite", routed through the central interface.
 *
 * Organization owners and managers are decided once at the organization. Team admins reach this
 * action too, and before ENG-1737 their capability was established only by `getTeamsWhereUserIsAdmin`.
 * `team.manage` is that capability, asked once per requested team so the answer
 * covers exactly the teams the invite would write to.
 *
 * Distinct ids, checked one at a time, stopping at the first refusal: asking per team makes the
 * number of authorization decisions follow the request body, so repeats are collapsed (naming a team
 * twice asks the same question twice) and the array is capped in the schema. Sequential rather than
 * `Promise.all` for the same reason — a request naming many teams should not fan out that many
 * concurrent checks, and the answer is available as soon as one team is refused.
 *
 * The narrower rules stay with the caller, in `validateTeamAdminInvitePermissions`: which invitation
 * role a team admin may grant, and that they must name at least one team, are policy about the
 * request's content rather than capabilities the vocabulary expresses.
 */
const assertInviterMayInvite = async ({
  isOrgOwnerOrManager,
  organizationId,
  teamIds,
  userId,
}: Readonly<{
  isOrgOwnerOrManager: boolean;
  organizationId: string;
  teamIds: ReadonlyArray<string>;
  userId: string;
}>): Promise<void> => {
  if (isOrgOwnerOrManager) {
    await assertUserManagementAllowed(userId, organizationId);
    await assertCan({ type: "user", id: userId }, "organization.manage", {
      type: "organization",
      id: organizationId,
    });
    return;
  }

  const actor = { type: "user", id: userId } as const;

  for (const teamId of new Set(teamIds)) {
    if (!(await can(actor, "team.manage", { type: "team", id: teamId }))) {
      throw new OperationNotAllowedError("Team admins can only add users to teams where they are admin");
    }
  }
};

const ZInviteUserAction = z.object({
  organizationId: ZId,
  // One address: anything else would let one invite, and one unit of the invite budget, reach several
  // inboxes (ENG-6658). Bulk and onboarding invites already validate the same way.
  email: ZUserEmail,
  name: z.string().trim().min(1, "Name is required"),
  role: ZOrganizationRole,
  // Bounded because a team admin's authorization is now decided per named team: without a cap the
  // number of authorization decisions would follow the request body. The UI offers the teams the
  // inviter can see, so this is far above any real selection.
  teamIds: z.array(ZId).max(INVITE_MAX_TEAMS, `An invite is limited to ${INVITE_MAX_TEAMS} teams`),
});

export const inviteUserAction = authenticatedActionClient.inputSchema(ZInviteUserAction).action(
  withAuditLogging("created", "invite", async ({ ctx, parsedInput }) => {
    if (INVITE_DISABLED) {
      throw new AuthenticationError("Invite disabled");
    }

    if (!IS_FORMBRICKS_CLOUD && parsedInput.role === OrganizationRole.billing) {
      throw new ValidationError("Billing role is not allowed");
    }

    const currentUserMembership = await getMembershipByUserIdOrganizationId(
      ctx.user.id,
      parsedInput.organizationId
    );
    if (!currentUserMembership) {
      throw new AuthenticationError("User not a member of this organization");
    }

    const isOrgOwnerOrManager =
      currentUserMembership.role === "owner" || currentUserMembership.role === "manager";

    // Fetch user's admin teams (empty array if owner/manager to skip unnecessary query)
    const userAdminTeams = isOrgOwnerOrManager
      ? []
      : await getTeamsWhereUserIsAdmin(ctx.user.id, parsedInput.organizationId);

    const isTeamAdmin = userAdminTeams.length > 0;

    if (!isOrgOwnerOrManager && !isTeamAdmin) {
      throw new AuthenticationError("Not authorized to invite members");
    }

    await assertInviterMayInvite({
      isOrgOwnerOrManager,
      organizationId: parsedInput.organizationId,
      teamIds: parsedInput.teamIds,
      userId: ctx.user.id,
    });

    // Validate team admin restrictions
    validateTeamAdminInvitePermissions(
      currentUserMembership.role,
      userAdminTeams,
      parsedInput.role,
      parsedInput.teamIds
    );

    // Owners and Managers give roles by the one shared rule (C10); a team admin's invite was held to
    // Member by `validateTeamAdminInvitePermissions` above.
    if (isOrgOwnerOrManager) {
      await assertCanAssignRole({
        organizationId: parsedInput.organizationId,
        assignerRole: currentUserMembership.role,
        roles: [parsedInput.role],
      });
    }

    if (parsedInput.role !== "owner" || parsedInput.teamIds.length > 0) {
      await checkRoleManagementPermission(parsedInput.organizationId);
    }

    const rateLimitReservation = await reserveInviteRateLimit(parsedInput.organizationId, ctx.user.id);

    let inviteId: Awaited<ReturnType<typeof inviteUser>>;
    try {
      inviteId = await inviteUser({
        organizationId: parsedInput.organizationId,
        invitee: {
          email: parsedInput.email,
          name: parsedInput.name,
          role: parsedInput.role,
          teamIds: parsedInput.teamIds,
        },
        currentUserId: ctx.user.id,
      });
    } catch (error) {
      await settleInviteRateLimit(rateLimitReservation, 0);
      throw error;
    }
    await settleInviteRateLimit(rateLimitReservation, inviteId ? 1 : 0);

    ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
    ctx.auditLoggingCtx.inviteId = inviteId;
    ctx.auditLoggingCtx.newObject = {
      email: parsedInput.email,
      name: parsedInput.name,
      role: parsedInput.role,
      teamIds: parsedInput.teamIds,
    };

    if (inviteId) {
      // Email delivery is best-effort: the invite is already persisted and can be shared via its
      // link, so a failing/misconfigured SMTP must not fail the whole action — otherwise the created
      // invite is stranded behind an "Invite already exists" error on the user's next attempt.
      try {
        await sendInviteMemberEmail(
          inviteId,
          parsedInput.email,
          ctx.user.name ?? "",
          parsedInput.name ?? "",
          parsedInput.organizationId,
          ctx.user.id
        );
      } catch (error) {
        logger.error(error, "Failed to send invite email");
      }
    }

    capturePostHogEvent(
      ctx.user.id,
      "team_member_invited",
      {
        organization_id: parsedInput.organizationId,
        invitee_role: parsedInput.role,
      },
      { organizationId: parsedInput.organizationId }
    );

    return inviteId;
  })
);

const ZBulkInviteUsersAction = z.object({
  organizationId: ZId,
  invitees: ZInvitees,
});

export const bulkInviteUsersAction = authenticatedActionClient.inputSchema(ZBulkInviteUsersAction).action(
  withAuditLogging("created", "invite", async ({ ctx, parsedInput }) => {
    if (INVITE_DISABLED) {
      throw new AuthenticationError("Invite disabled");
    }

    const { organizationId, invitees } = parsedInput;

    if (invitees.length === 0) {
      throw new ValidationError("No invitees provided");
    }

    if (invitees.length > BULK_INVITE_MAX_INVITEES) {
      throw new ValidationError(`A bulk invite is limited to ${BULK_INVITE_MAX_INVITEES} members at a time`);
    }

    // Bulk invite is restricted to organization owners and managers.
    const currentUserMembership = await getMembershipByUserIdOrganizationId(ctx.user.id, organizationId);
    if (!currentUserMembership) {
      throw new AuthenticationError("User not a member of this organization");
    }

    await assertUserManagementAllowed(ctx.user.id, organizationId);
    await assertCan({ type: "user", id: ctx.user.id }, "organization.manage", {
      type: "organization",
      id: organizationId,
    });

    // Entitlement gate: bulk invite is a paid feature. Mitigates the invite-spam abuse vector by
    // keeping high-volume invites behind the bulk-invite entitlement (Stripe on cloud, license
    // feature on self-hosted) rather than hardcoding plan names.
    const isBulkInviteAllowed = await getBulkInvitePermission(organizationId);
    if (!isBulkInviteAllowed) {
      throw new OperationNotAllowedError("Bulk invite is not available on your current plan");
    }

    // Validate roles for the whole batch up front, by the one shared rule (C10).
    await assertCanAssignRole({
      organizationId,
      assignerRole: currentUserMembership.role,
      roles: invitees.map((invitee) => invitee.role),
    });

    if (invitees.some((invitee) => invitee.role !== "owner" || (invitee.teamIds ?? []).length > 0)) {
      await checkRoleManagementPermission(organizationId);
    }

    const rateLimitReservation = await reserveInviteRateLimit(organizationId, ctx.user.id, invitees.length);

    const results: TBulkInviteResult[] = [];
    const invitedEmails: string[] = [];

    try {
      for (const invitee of invitees) {
        const email = invitee.email.toLowerCase();
        try {
          const inviteId = await inviteUser({
            organizationId,
            invitee: { ...invitee, email },
            currentUserId: ctx.user.id,
          });

          if (inviteId) {
            // Best-effort email (see inviteUserAction): a failed send must not flip a created invite
            // to "failed" — the invitee exists and can be reached via the invite link.
            try {
              await sendInviteMemberEmail(
                inviteId,
                email,
                ctx.user.name ?? "",
                invitee.name ?? "",
                organizationId,
                ctx.user.id
              );
            } catch (error) {
              logger.error(error, "Failed to send bulk invite email");
            }
            invitedEmails.push(email);
            results.push({ email, success: true });
          } else {
            results.push({ email, success: false, failureReason: "unknown" });
          }
        } catch (error) {
          results.push({ email, success: false, failureReason: getInviteFailureReason(error) });
        }
      }
    } finally {
      await settleInviteRateLimit(rateLimitReservation, invitedEmails.length);
    }

    ctx.auditLoggingCtx.organizationId = organizationId;
    ctx.auditLoggingCtx.newObject = {
      invitedCount: invitedEmails.length,
      totalCount: invitees.length,
      emails: invitedEmails,
    };

    capturePostHogEvent(
      ctx.user.id,
      "team_members_bulk_invited",
      {
        organization_id: organizationId,
        invited_count: invitedEmails.length,
        total_count: invitees.length,
      },
      { organizationId }
    );

    return results;
  })
);

const ZLeaveOrganizationAction = z.object({
  organizationId: ZId,
});

export const leaveOrganizationAction = authenticatedActionClient.inputSchema(ZLeaveOrganizationAction).action(
  withAuditLogging("deleted", "membership", async ({ ctx, parsedInput }) => {
    // Leaving needs nothing but the caller's own membership. Not `organization.read`: SpiceDB denies it
    // to a Dashboard viewer (ADR-0025), who must still be able to leave the organization.
    const membership = await getMembershipByUserIdOrganizationId(ctx.user.id, parsedInput.organizationId);

    if (!membership) {
      throw new AuthenticationError("Not a member of this organization");
    }

    await applyRateLimit(rateLimitConfigs.actions.stateMutation, parsedInput.organizationId);

    const { isOwner } = getAccessFlags(membership.role);

    const isMultiOrgEnabled = await getIsMultiOrgEnabled();

    if (isOwner) {
      throw new OperationNotAllowedError("You cannot leave an organization you own");
    }

    if (!isMultiOrgEnabled) {
      throw new OperationNotAllowedError(
        "You cannot leave the organization because you are the only owner and organization deletion is disabled"
      );
    }

    const memberships = await getMembershipsByUserId(ctx.user.id);
    if (!memberships || memberships?.length <= 1) {
      throw new ValidationError("You cannot leave the only organization you are a member of");
    }

    ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
    ctx.auditLoggingCtx.membershipId = `${ctx.user.id}-${parsedInput.organizationId}`;
    ctx.auditLoggingCtx.oldObject = membership;

    return await deleteMembership(ctx.user.id, parsedInput.organizationId, ctx.user.id);
  })
);
