"use server";

import { z } from "zod";
import { ZId, ZStorageUrl } from "@formbricks/types/common";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";
import { checkWhiteLabelPermission } from "@/modules/ee/whitelabel/email-customization/actions";
import { updateOrganizationFaviconUrl } from "@/modules/ee/whitelabel/favicon-customization/lib/organization";

const ZUpdateOrganizationFaviconUrlAction = z.object({
  organizationId: ZId,
  faviconUrl: ZStorageUrl,
});

export const updateOrganizationFaviconUrlAction = authenticatedActionClient
  .inputSchema(ZUpdateOrganizationFaviconUrlAction)
  .action(
    withAuditLogging("updated", "organization", async ({ ctx, parsedInput }) => {
      const { organizationId, faviconUrl } = parsedInput;

      await checkAuthorizationUpdated({
        userId: ctx.user.id,
        organizationId,
        access: [
          {
            type: "organization",
            roles: ["owner", "manager"],
          },
        ],
      });

      await checkWhiteLabelPermission(organizationId);

      ctx.auditLoggingCtx.organizationId = organizationId;
      ctx.auditLoggingCtx.newObject = { faviconUrl };

      return await updateOrganizationFaviconUrl(organizationId, faviconUrl);
    })
  );

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

export const removeOrganizationFaviconUrlAction = authenticatedActionClient
  .inputSchema(ZRemoveOrganizationFaviconUrlAction)
  .action(
    withAuditLogging("updated", "organization", async ({ ctx, parsedInput }) => {
      const { organizationId } = parsedInput;

      await checkAuthorizationUpdated({
        userId: ctx.user.id,
        organizationId,
        access: [{ type: "organization", roles: ["owner", "manager"] }],
      });

      await checkWhiteLabelPermission(organizationId);

      ctx.auditLoggingCtx.organizationId = organizationId;
      ctx.auditLoggingCtx.oldObject = { faviconUrl: "" };

      return await updateOrganizationFaviconUrl(organizationId, null);
    })
  );
