"use server";

import { z } from "zod";
import { ZId, ZStorageUrl } from "@formbricks/types/common";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { assertCan } from "@/lib/authorization";
import { getOrganization } from "@/lib/organization/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
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 {
  removeOrganizationEmailLogoUrl,
  updateOrganizationEmailLogoUrl,
} from "@/modules/ee/whitelabel/email-customization/lib/organization";
import { checkWhiteLabelPermission } from "@/modules/ee/whitelabel/email-customization/lib/permission";
import { sendEmailCustomizationPreviewEmail } from "@/modules/email";

const ZUpdateOrganizationEmailLogoUrlAction = z.object({
  organizationId: ZId,
  logoUrl: ZStorageUrl,
});

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

      await checkWhiteLabelPermission(parsedInput.organizationId);
      ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
      ctx.auditLoggingCtx.newObject = { logoUrl: parsedInput.logoUrl };
      return await updateOrganizationEmailLogoUrl(parsedInput.organizationId, parsedInput.logoUrl);
    })
  );

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

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

      await checkWhiteLabelPermission(parsedInput.organizationId);
      ctx.auditLoggingCtx.organizationId = parsedInput.organizationId;
      ctx.auditLoggingCtx.oldObject = { logoUrl: "" };
      return await removeOrganizationEmailLogoUrl(parsedInput.organizationId);
    })
  );

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

export const sendTestEmailAction = authenticatedActionClient
  .inputSchema(ZSendTestEmailAction)
  .action(async ({ ctx, parsedInput }) => {
    const organization = await getOrganization(parsedInput.organizationId);

    if (!organization) {
      throw new ResourceNotFoundError("Organization", parsedInput.organizationId);
    }

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

    await checkWhiteLabelPermission(organization.id);

    await sendEmailCustomizationPreviewEmail(
      ctx.user.email,
      ctx.user.name,
      ctx.user.locale,
      ctx.user.id,
      organization?.whitelabel?.logoUrl || "",
      organization.id
    );

    return { success: true };
  });
