import { z } from "zod";

const hexSchema = z
  .string()
  .regex(/^[0-9a-fA-F]{24}$/, "Invalid organization ID");

export default defineNuxtPlugin(() => {
  const router = useRouter();
  const { getByUserType } = useMember();
  const { getRoleById } = useRole();
  const { getById } = useOrg();

  const { userAppRole, id, orgNature } = useLocalSetup();

  router.afterEach(async (to) => {
    const isMember = to.meta?.memberOnly;

    if (!isMember) return;

    const APP = useRuntimeConfig().public.APP;
    const org = computed(
      () =>
        (to.params.org as string) || (to.params.organization as string) || ""
    );

    console.log('[secure-member-plugin', 'org', org.value)

    if (!hexSchema.safeParse(org.value).success) {
      return router.replace({ name: "require-organization-membership" });
    }

    const userId = computed(() => useCookie("user").value ?? "");

    const { data: userMemberData, error: userMemberError } =
      await useLazyAsyncData(
        "plugin-get-member-by-id-" + userId.value + "-" + APP + "-" + org.value,
        () => getByUserType(userId.value, APP, org.value),
        { watch: [userId] }
      );

    watchEffect(() => {
      if (userMemberError.value) {
        console.log('running-secure-member-redirect-plugin')
        navigateTo(
          {
            name: "index",
          },
          { replace: true }
        );
      }
    });

    const roleId = ref("roleId");

    watchEffect(() => {
      if (userMemberData.value) {
        id.value = userMemberData.value.org ?? "";
        roleId.value = userMemberData.value.role ?? "roleId";
      }
    });

    const { data: getOrgByIdReq } = await useLazyAsyncData(
      "plugin-get-org-by-id-" + org.value,
      () => getById(org.value),
      { watch: [org] }
    );

    watchEffect(() => {
      if (getOrgByIdReq.value) {
        orgNature.value = getOrgByIdReq.value.nature ?? "";
      }
    });

    const { data: getRoleByIdReq } = await useLazyAsyncData(
      "plugin-get-role-by-id-" + roleId.value,
      () => getRoleById(roleId.value),
      { watch: [roleId] }
    );

    watchEffect(() => {
      if (getRoleByIdReq.value) {
        userAppRole.value = getRoleByIdReq.value;
      }
    });
  });
});
