import { notFound, redirect } from "next/navigation";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { AuthenticationError, ResourceNotFoundError } from "@formbricks/types/errors";
import type { TOrganizationRole } from "@formbricks/types/memberships";
import { can } from "@/lib/authorization";
import { getBillingFallbackPath } from "@/lib/membership/navigation";
import { getMembershipByUserIdOrganizationId } from "@/lib/membership/service";
import { getOrganization } from "@/lib/organization/service";
import { getMonthlyOrganizationResponseCount } from "@/lib/organization/service";
import { getUser } from "@/lib/user/service";
import { canUserNavigateWorkspace } from "@/lib/workspace/auth";
import { getWorkspace } from "@/lib/workspace/service";
import { getSession } from "@/modules/auth/lib/session";
import { getDashboardViewerWorkspaceState } from "@/modules/ee/analysis/lib/dashboard-viewer-access";
import { getEnterpriseLicense } from "@/modules/ee/license-check/lib/license";
import { getAccessControlPermission } from "@/modules/ee/license-check/lib/utils";
import { getWorkspacePermissionByUserId } from "@/modules/ee/teams/lib/roles";
import { getWorkspaceAuth, getWorkspaceLayoutData, workspaceIdLayoutChecks } from "./utils";

const mocks = vi.hoisted(() => ({ isFormbricksCloud: false, workspaceFindUnique: vi.fn() }));

// Real getAccessFlags and getTeamPermissionFlags are used on purpose so the tests exercise the
// actual role -> isBilling mapping (the redirect branch) and the permission -> isReadOnly mapping.
// Everything else getWorkspaceAuth touches is stubbed. `redirect` is a no-op spy; `notFound` throws, as
// the real one does, so a 404 ends the helper instead of falling through.
vi.mock("next/navigation", () => ({
  redirect: vi.fn(),
  notFound: vi.fn(() => {
    throw new Error("NEXT_NOT_FOUND");
  }),
}));
vi.mock("react", () => ({ cache: (fn: (...args: unknown[]) => unknown) => fn }));
vi.mock("@/lib/constants", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@/lib/constants")>()),
  get IS_FORMBRICKS_CLOUD() {
    return mocks.isFormbricksCloud;
  },
}));
vi.mock("@/lib/workspace/service", () => ({ getWorkspace: vi.fn() }));
vi.mock("@/lib/authorization", () => ({ can: vi.fn() }));
vi.mock("@/lib/workspace/auth", () => ({ canUserNavigateWorkspace: vi.fn() }));
vi.mock("@formbricks/database", () => ({ prisma: { workspace: { findUnique: mocks.workspaceFindUnique } } }));
vi.mock("@/lib/user/service", () => ({ getUser: vi.fn() }));
vi.mock("@/modules/ee/license-check/lib/utils", () => ({ getAccessControlPermission: vi.fn() }));
vi.mock("@/modules/ee/license-check/lib/license", () => ({ getEnterpriseLicense: vi.fn() }));
vi.mock("@/lib/organization/service", () => ({
  getOrganization: vi.fn(),
  getMonthlyOrganizationResponseCount: vi.fn(),
}));
vi.mock("@/lib/membership/service", () => ({ getMembershipByUserIdOrganizationId: vi.fn() }));
vi.mock("@/lib/membership/navigation", () => ({ getBillingFallbackPath: vi.fn() }));
vi.mock("@/lingodotdev/server", () => ({ getTranslate: vi.fn(() => Promise.resolve((k: string) => k)) }));
vi.mock("@/modules/auth/lib/session", () => ({ getSession: vi.fn() }));
vi.mock("@/modules/ee/analysis/lib/dashboard-viewer-access", () => ({
  getDashboardViewerWorkspaceState: vi.fn(async () => "none"),
}));
vi.mock("@/modules/ee/teams/lib/roles", () => ({ getWorkspacePermissionByUserId: vi.fn() }));

const workspaceId = "workspace-1";
const organizationId = "organization-1";
const userId = "user-1";
const billingFallbackPath = `/organizations/${organizationId}/settings/enterprise`;

const primeAuth = (role: TOrganizationRole) => {
  vi.mocked(getWorkspace).mockResolvedValue({ id: workspaceId, organizationId } as Awaited<
    ReturnType<typeof getWorkspace>
  >);
  vi.mocked(getSession).mockResolvedValue({
    user: { id: userId },
    expires: new Date(0).toISOString(),
  });
  vi.mocked(getOrganization).mockResolvedValue({ id: organizationId } as Awaited<
    ReturnType<typeof getOrganization>
  >);
  vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue({
    role,
    organizationId,
    userId,
    accepted: true,
  });
  vi.mocked(can).mockResolvedValue(true);
  vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue(null);
  vi.mocked(getBillingFallbackPath).mockReturnValue(billingFallbackPath);
};

describe("getWorkspaceAuth billing gate (ENG-1763)", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  test("redirects a billing-role member to the billing fallback path", async () => {
    primeAuth("billing");

    await getWorkspaceAuth(workspaceId);

    expect(getBillingFallbackPath).toHaveBeenCalledWith(organizationId, mocks.isFormbricksCloud);
    expect(redirect).toHaveBeenCalledWith(billingFallbackPath);
  });

  test.each<TOrganizationRole>(["owner", "manager", "member"])(
    "does not redirect a %s member",
    async (role) => {
      primeAuth(role);

      const result = await getWorkspaceAuth(workspaceId);

      expect(redirect).not.toHaveBeenCalled();
      expect(getBillingFallbackPath).not.toHaveBeenCalled();
      expect(result.isBilling).toBe(false);
    }
  );
});

describe("getWorkspaceAuth Dashboard viewer gate (ADR-0025)", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  test("sends a Dashboard viewer to the workspace's dashboard list before any product data is read", async () => {
    primeAuth("dashboard_viewer");
    vi.mocked(redirect).mockImplementation(() => {
      throw new Error("NEXT_REDIRECT");
    });

    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow("NEXT_REDIRECT");

    expect(redirect).toHaveBeenCalledWith(`/workspaces/${workspaceId}/dashboards`);
    expect(can).not.toHaveBeenCalled();
    expect(getWorkspacePermissionByUserId).not.toHaveBeenCalled();
    vi.mocked(redirect).mockReset();
  });
});

describe("getWorkspaceAuth workspace-access gate + isReadOnly (ENG-1769)", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    // Happy-path default: an org member with read-only workspace access.
    primeAuth("member");
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue("read");
  });

  test("404s when the workspace is missing", async () => {
    vi.mocked(getWorkspace).mockResolvedValue(null);
    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow("NEXT_NOT_FOUND");
    expect(notFound).toHaveBeenCalled();
  });

  test("throws AuthenticationError when there is no session", async () => {
    vi.mocked(getSession).mockResolvedValue(null);
    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow(AuthenticationError);
  });

  test("throws ResourceNotFoundError when the organization is missing", async () => {
    vi.mocked(getOrganization).mockResolvedValue(null);
    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow(ResourceNotFoundError);
  });

  test("404s when the user has no org membership", async () => {
    vi.mocked(getMembershipByUserIdOrganizationId).mockResolvedValue(null);
    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow("NEXT_NOT_FOUND");
  });

  // The core fix: an org member with no WorkspaceTeam grant for this workspace
  // must be rejected instead of being admitted (and mislabeled as a writer).
  test("404s when the user has no workspace access", async () => {
    vi.mocked(can).mockResolvedValue(false);
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue(null);
    await expect(getWorkspaceAuth(workspaceId)).rejects.toThrow("NEXT_NOT_FOUND");
    // The narrow read permission, not the navigation check: billing has already been
    // redirected above, so this choke point must not re-admit it.
    expect(can).toHaveBeenCalledWith({ type: "user", id: userId }, "workspace.read", {
      type: "workspace",
      id: workspaceId,
    });
  });

  test("marks a member with a read grant as read-only", async () => {
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue("read");
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.isMember).toBe(true);
    expect(auth.hasReadAccess).toBe(true);
    expect(auth.isReadOnly).toBe(true);
  });

  test("does not mark a member with a readWrite grant as read-only", async () => {
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue("readWrite");
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.hasReadWriteAccess).toBe(true);
    expect(auth.isReadOnly).toBe(false);
  });

  test("does not mark a member with a manage grant as read-only", async () => {
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue("manage");
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.hasManageAccess).toBe(true);
    expect(auth.isReadOnly).toBe(false);
  });

  // Fail-safe: even if a member reaches the flags with no resolved permission,
  // isReadOnly must be true (most restricted), never false (writer).
  test("treats a member with no resolved permission as read-only (fail safe)", async () => {
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue(null);
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.isMember).toBe(true);
    expect(auth.hasReadAccess).toBe(false);
    expect(auth.hasReadWriteAccess).toBe(false);
    expect(auth.hasManageAccess).toBe(false);
    expect(auth.isReadOnly).toBe(true);
  });

  test("does not mark an owner as read-only", async () => {
    primeAuth("owner");
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue(null);
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.isOwner).toBe(true);
    expect(auth.isReadOnly).toBe(false);
  });

  // canManage mirrors `workspace.manage` (ENG-3191): a readWrite member may write but not manage.
  test.each([
    ["member", "read", false],
    ["member", "readWrite", false],
    ["member", "manage", true],
    ["member", null, false],
    ["owner", null, true],
    ["manager", null, true],
  ] as const)("canManage for a %s with a %s grant is %s", async (role, permission, expected) => {
    primeAuth(role);
    vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue(permission);
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.canManage).toBe(expected);
  });

  test("returns the resolved workspace, organization, and session on success", async () => {
    const auth = await getWorkspaceAuth(workspaceId);
    expect(auth.workspace).toMatchObject({ id: workspaceId, organizationId });
    expect(auth.organization).toMatchObject({ id: organizationId });
    expect(auth.session.user.id).toBe(userId);
    expect(auth.workspacePermission).toBe("read");
  });
});

// The layout helpers gate navigation rather than data, so unlike getWorkspaceAuth they must keep
// admitting the billing role — that is how it reaches the billing screens. These ids are real
// cuid2s because getWorkspaceLayoutData validates them.
describe("layout navigation gates (ENG-1737)", () => {
  const layoutWorkspaceId = "cl9ebqhxk00003b600tymydho";
  const layoutOrganizationId = "cl9ebqhxk00013b60vqhmydho";
  const layoutUserId = "cl9ebqhxk00023b60kzlmydho";

  const organizationRelation = {
    id: layoutOrganizationId,
    createdAt: new Date(0),
    updatedAt: new Date(0),
    name: "Org",
    billing: { stripeCustomerId: null, limits: {}, usageCycleAnchor: null, stripe: null },
    isAISmartToolsEnabled: false,
    whitelabel: null,
    displayTimeZone: "Europe/Berlin",
  };

  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(getSession).mockResolvedValue({
      user: { id: layoutUserId },
      expires: new Date(0).toISOString(),
    });
    vi.mocked(getUser).mockResolvedValue({ id: layoutUserId } as Awaited<ReturnType<typeof getUser>>);
    vi.mocked(canUserNavigateWorkspace).mockResolvedValue(true);
    mocks.workspaceFindUnique.mockResolvedValue({ organization: organizationRelation });
  });

  describe("workspaceIdLayoutChecks", () => {
    test("asks the navigation question about the resolved workspace and its organization", async () => {
      const result = await workspaceIdLayoutChecks(layoutWorkspaceId);

      expect(canUserNavigateWorkspace).toHaveBeenCalledWith(layoutUserId, {
        id: layoutWorkspaceId,
        organizationId: layoutOrganizationId,
      });
      expect(result.organization).toMatchObject({ id: layoutOrganizationId });
    });

    test("404s when the user may not navigate there", async () => {
      vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);

      await expect(workspaceIdLayoutChecks(layoutWorkspaceId)).rejects.toThrow("NEXT_NOT_FOUND");
    });

    test("sends a Dashboard viewer of the workspace to its dashboards instead of the editor", async () => {
      vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);
      vi.mocked(getDashboardViewerWorkspaceState).mockResolvedValueOnce("granted");

      await workspaceIdLayoutChecks(layoutWorkspaceId);

      expect(redirect).toHaveBeenCalledWith(`/workspaces/${layoutWorkspaceId}/dashboards`);
    });

    // Existence is answered before access, so a missing workspace 404s without an access decision —
    // matching getWorkspaceAuth.
    test("404s for a workspace that does not exist", async () => {
      mocks.workspaceFindUnique.mockResolvedValue(null);

      await expect(workspaceIdLayoutChecks(layoutWorkspaceId)).rejects.toThrow("NEXT_NOT_FOUND");
      expect(canUserNavigateWorkspace).not.toHaveBeenCalled();
    });

    test("returns early without deciding access when there is no session", async () => {
      vi.mocked(getSession).mockResolvedValue(null);

      const result = await workspaceIdLayoutChecks(layoutWorkspaceId);

      expect(result.session).toBeNull();
      expect(canUserNavigateWorkspace).not.toHaveBeenCalled();
    });
  });

  describe("getWorkspaceLayoutData", () => {
    beforeEach(() => {
      mocks.workspaceFindUnique.mockResolvedValue({
        id: layoutWorkspaceId,
        organizationId: layoutOrganizationId,
        organization: { ...organizationRelation, memberships: [{ userId: layoutUserId, role: "member" }] },
      });
      vi.mocked(getAccessControlPermission).mockResolvedValue(false);
      vi.mocked(getWorkspacePermissionByUserId).mockResolvedValue("read");
      vi.mocked(getEnterpriseLicense).mockResolvedValue({ active: false } as Awaited<
        ReturnType<typeof getEnterpriseLicense>
      >);
    });

    test("asks the navigation question about the resolved workspace and its organization", async () => {
      await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

      expect(canUserNavigateWorkspace).toHaveBeenCalledWith(layoutUserId, {
        id: layoutWorkspaceId,
        organizationId: layoutOrganizationId,
      });
    });

    // The organization is rebuilt field by field, and `displayTimeZone` is optional on its type, so dropping
    // it compiles cleanly — which is how every date filter silently fell back to UTC once (ENG-3215).
    test("carries the organization's display time zone to the layout, where the date filters read it", async () => {
      const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

      expect(data.organization.displayTimeZone).toBe("Europe/Berlin");
    });

    test("404s when the user may not navigate there", async () => {
      vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);

      await expect(getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId)).rejects.toThrow("NEXT_NOT_FOUND");
      // Only a Dashboard viewer's membership consults the viewer grant.
      expect(getDashboardViewerWorkspaceState).not.toHaveBeenCalled();
    });

    test.each(["granted", "lapsed"] as const)(
      "renders the shell for a Dashboard viewer whose team is granted the workspace (%s)",
      async (state) => {
        vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);
        mocks.workspaceFindUnique.mockResolvedValue({
          id: layoutWorkspaceId,
          organizationId: layoutOrganizationId,
          organization: {
            ...organizationRelation,
            memberships: [{ userId: layoutUserId, role: "dashboard_viewer" }],
          },
        });
        vi.mocked(getDashboardViewerWorkspaceState).mockResolvedValueOnce(state);

        const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

        expect(data.membership.role).toBe("dashboard_viewer");
      }
    );

    test("sends a Dashboard viewer no billing or Stripe detail and no Cloud response count", async () => {
      mocks.isFormbricksCloud = true;
      try {
        vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);
        mocks.workspaceFindUnique.mockResolvedValue({
          id: layoutWorkspaceId,
          organizationId: layoutOrganizationId,
          organization: {
            ...organizationRelation,
            billing: {
              stripeCustomerId: "cus_secret",
              limits: { workspaces: 9, monthly: { responses: 9000, workflowRuns: null } },
              usageCycleAnchor: new Date(0),
              stripe: { subscriptionId: "sub_secret" },
            },
            memberships: [{ userId: layoutUserId, role: "dashboard_viewer" }],
          },
        });
        vi.mocked(getDashboardViewerWorkspaceState).mockResolvedValueOnce("granted");

        const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

        expect(data.organization.billing.stripeCustomerId).toBeNull();
        expect(data.organization.billing.stripe).toBeUndefined();
        expect(data.organization.billing.usageCycleAnchor).toBeNull();
        expect(JSON.stringify(data.organization)).not.toMatch(/secret|9000/);
        expect(data.responseCount).toBe(0);
        expect(getMonthlyOrganizationResponseCount).not.toHaveBeenCalled();
      } finally {
        mocks.isFormbricksCloud = false;
      }
    });

    const mockOrganizationBilling = (billing: Record<string, unknown>) =>
      mocks.workspaceFindUnique.mockResolvedValue({
        id: layoutWorkspaceId,
        organizationId: layoutOrganizationId,
        organization: {
          ...organizationRelation,
          billing: { stripeCustomerId: null, usageCycleAnchor: null, stripe: null, ...billing },
          memberships: [{ userId: layoutUserId, role: "member" }],
        },
      });

    test("keeps billing and the Cloud response count for everyone else", async () => {
      mocks.isFormbricksCloud = true;
      try {
        mockOrganizationBilling({
          limits: { workspaces: 3, monthly: { responses: 250, workflowRuns: null } },
        });
        vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(42);

        const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

        expect(data.responseCount).toBe(42);
      } finally {
        mocks.isFormbricksCloud = false;
      }
    });

    // The count scans the whole cycle's responses; on a plan with no response limit nothing reads it (ENG-3789).
    test("skips the Cloud response count when the plan has no response limit", async () => {
      mocks.isFormbricksCloud = true;
      try {
        mockOrganizationBilling({
          limits: { workspaces: null, monthly: { responses: null, workflowRuns: null } },
        });
        vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(42);

        const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

        expect(data.responseCount).toBe(0);
        expect(getMonthlyOrganizationResponseCount).not.toHaveBeenCalled();
      } finally {
        mocks.isFormbricksCloud = false;
      }
    });

    test("still counts for a trialing organization without a response limit, whose trial card shows it", async () => {
      mocks.isFormbricksCloud = true;
      try {
        mockOrganizationBilling({
          limits: { workspaces: null, monthly: { responses: null, workflowRuns: null } },
          stripe: { subscriptionStatus: "trialing" },
        });
        vi.mocked(getMonthlyOrganizationResponseCount).mockResolvedValue(42);

        const data = await getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId);

        expect(data.responseCount).toBe(42);
      } finally {
        mocks.isFormbricksCloud = false;
      }
    });

    test("404s for a Dashboard viewer none of whose teams is granted the workspace", async () => {
      vi.mocked(canUserNavigateWorkspace).mockResolvedValue(false);
      mocks.workspaceFindUnique.mockResolvedValue({
        id: layoutWorkspaceId,
        organizationId: layoutOrganizationId,
        organization: {
          ...organizationRelation,
          memberships: [{ userId: layoutUserId, role: "dashboard_viewer" }],
        },
      });

      await expect(getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId)).rejects.toThrow("NEXT_NOT_FOUND");
    });

    test("404s for a workspace that does not exist", async () => {
      mocks.workspaceFindUnique.mockResolvedValue(null);

      await expect(getWorkspaceLayoutData(layoutWorkspaceId, layoutUserId)).rejects.toThrow("NEXT_NOT_FOUND");
      expect(canUserNavigateWorkspace).not.toHaveBeenCalled();
    });
  });
});
