"use server";

import { z } from "zod";
import { prisma } from "@formbricks/database";
import { ZId } from "@formbricks/types/common";
import { AuthorizationError, InvalidInputError, ResourceNotFoundError } from "@formbricks/types/errors";
import {
  ZFeedbackSourceCreateInput,
  ZFeedbackSourceFieldMappingCreateInput,
  ZFeedbackSourceUpdateInput,
} from "@formbricks/types/feedback-source";
import { assertCan } from "@/lib/authorization";
import { getResponseCountBySurveyId } from "@/lib/response/service";
import { getSurvey } from "@/lib/survey/service";
import { assertNewlyAttachedSurveysWorkspaceVisible } from "@/lib/survey/visibility/outbound";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
import {
  getOrganizationIdFromFeedbackSourceId,
  getOrganizationIdFromWorkspaceId,
  getWorkspaceIdFromSurveyId,
} 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 { getContactIdsByUserIds } from "@/modules/ee/unify-feedback/lib/contacts";
import { assertFeedbackSourceDirectoryAccess } from "./access";
import { importHistoricalResponses } from "./import";
import { resolveFormbricksMappingsInput } from "./mappings";
import {
  TMappingsInput,
  createFeedbackSourceWithMappings,
  deleteFeedbackSource,
  getFeedbackSourceWithMappingsById,
  updateFeedbackSourceWithMappings,
} from "./service";
import {
  formatMissingRequiredCsvFieldMappingsMessage,
  getMissingRequiredCsvFieldMappings,
  sanitizeCsvFieldMappings,
} from "./utils";

const ZDeleteFeedbackSourceAction = z.object({
  feedbackSourceId: ZId,
  workspaceId: ZId,
});

export const deleteFeedbackSourceAction = authenticatedActionClient
  .inputSchema(ZDeleteFeedbackSourceAction)
  .action(
    withAuditLogging("deleted", "feedbackSource", async ({ ctx, parsedInput }) => {
      ctx.auditLoggingCtx.feedbackSourceId = parsedInput.feedbackSourceId;
      ctx.auditLoggingCtx.workspaceId = parsedInput.workspaceId;
      await applyRateLimit(rateLimitConfigs.actions.feedbackSourceMutation, ctx.user.id);

      const organizationId = await getOrganizationIdFromFeedbackSourceId(parsedInput.feedbackSourceId);
      ctx.auditLoggingCtx.organizationId = organizationId;
      await assertCan({ type: "user", id: ctx.user.id }, "workspace.write", {
        type: "workspace",
        id: parsedInput.workspaceId,
      });

      const feedbackSource = await getFeedbackSourceWithMappingsById(
        parsedInput.feedbackSourceId,
        parsedInput.workspaceId
      );
      if (!feedbackSource) {
        throw new ResourceNotFoundError("FeedbackSource", parsedInput.feedbackSourceId);
      }
      await assertFeedbackSourceDirectoryAccess(
        ctx.user.id,
        feedbackSource.feedbackDirectoryId,
        parsedInput.workspaceId,
        "write"
      );

      const deletedFeedbackSource = await deleteFeedbackSource(
        parsedInput.feedbackSourceId,
        parsedInput.workspaceId
      );
      ctx.auditLoggingCtx.oldObject = deletedFeedbackSource;
      return deletedFeedbackSource;
    })
  );

const ZFormbricksSurveyMapping = z.object({
  surveyId: ZId,
  elementIds: z.array(z.string()).min(1),
});

const sanitizeAndValidateCsvFieldMappings = (
  fieldMappings: z.infer<typeof ZFeedbackSourceFieldMappingCreateInput>[]
) => {
  const sanitized = sanitizeCsvFieldMappings(fieldMappings) ?? [];
  const missing = getMissingRequiredCsvFieldMappings(sanitized);

  if (missing.length > 0) {
    throw new InvalidInputError(formatMissingRequiredCsvFieldMappingsMessage());
  }

  return sanitized;
};

const ZCreateFeedbackSourceWithMappingsAction = z
  .object({
    workspaceId: ZId,
    feedbackSourceInput: ZFeedbackSourceCreateInput,
    formbricksMappings: z.array(ZFormbricksSurveyMapping).optional(),
    fieldMappings: z.array(ZFeedbackSourceFieldMappingCreateInput).optional(),
  })
  .superRefine((data, ctx) => {
    if (data.feedbackSourceInput.type === "formbricks_survey") {
      if (!data.formbricksMappings?.length) {
        ctx.addIssue({
          code: "custom",
          path: ["formbricksMappings"],
          message: "At least one survey mapping is required for Formbricks feedbackSources",
        });
      }
    } else if (data.feedbackSourceInput.type === "csv") {
      if (!data.fieldMappings?.length) {
        ctx.addIssue({
          code: "custom",
          path: ["fieldMappings"],
          message: "At least one field mapping is required for CSV feedbackSources",
        });
      }
    }
  });

export const createFeedbackSourceWithMappingsAction = authenticatedActionClient
  .inputSchema(ZCreateFeedbackSourceWithMappingsAction)
  .action(
    withAuditLogging("created", "feedbackSource", async ({ ctx, parsedInput }) => {
      ctx.auditLoggingCtx.workspaceId = parsedInput.workspaceId;
      await applyRateLimit(rateLimitConfigs.actions.feedbackSourceMutation, ctx.user.id);

      const organizationId = await getOrganizationIdFromWorkspaceId(parsedInput.workspaceId);
      ctx.auditLoggingCtx.organizationId = organizationId;
      await assertCan({ type: "user", id: ctx.user.id }, "workspace.write", {
        type: "workspace",
        id: parsedInput.workspaceId,
      });

      // Verify the directory belongs to the same org and is actually assigned to this workspace.
      // The composite FK enforces the assignment at the DB level too; these checks return the
      // friendlier errors first: a generic auth error for missing/cross-org directories, a typed
      // error for a same-org directory that just isn't assigned to the workspace.
      const frd = await prisma.feedbackDirectory.findUnique({
        where: { id: parsedInput.feedbackSourceInput.feedbackDirectoryId },
        select: {
          organizationId: true,
          workspaces: {
            where: { workspaceId: parsedInput.workspaceId },
            select: { workspaceId: true },
          },
        },
      });
      if (frd?.organizationId !== organizationId) {
        throw new AuthorizationError("Invalid feedback directory");
      }
      if (frd.workspaces.length === 0) {
        throw new InvalidInputError("FEEDBACK_SOURCE_DIRECTORY_NOT_ASSIGNED_TO_WORKSPACE");
      }
      await assertFeedbackSourceDirectoryAccess(
        ctx.user.id,
        parsedInput.feedbackSourceInput.feedbackDirectoryId,
        parsedInput.workspaceId,
        "write"
      );

      let mappingsInput: TMappingsInput | undefined;

      const { formbricksMappings, fieldMappings } = parsedInput;

      if (formbricksMappings?.length) {
        mappingsInput = await resolveFormbricksMappingsInput(formbricksMappings, parsedInput.workspaceId);
      } else if (fieldMappings?.length) {
        mappingsInput = {
          type: "field",
          mappings:
            parsedInput.feedbackSourceInput.type === "csv"
              ? sanitizeAndValidateCsvFieldMappings(fieldMappings)
              : fieldMappings,
        };
      }

      const createdFeedbackSource = await createFeedbackSourceWithMappings(
        parsedInput.workspaceId,
        { ...parsedInput.feedbackSourceInput, createdBy: ctx.user.id },
        mappingsInput
      );
      ctx.auditLoggingCtx.feedbackSourceId = createdFeedbackSource.id;
      ctx.auditLoggingCtx.newObject = createdFeedbackSource;
      return createdFeedbackSource;
    })
  );

const ZUpdateFeedbackSourceWithMappingsAction = z.object({
  feedbackSourceId: ZId,
  workspaceId: ZId,
  feedbackSourceInput: ZFeedbackSourceUpdateInput,
  formbricksMappings: z.array(ZFormbricksSurveyMapping).min(1).optional(),
  fieldMappings: z.array(ZFeedbackSourceFieldMappingCreateInput).optional(),
});

export const updateFeedbackSourceWithMappingsAction = authenticatedActionClient
  .inputSchema(ZUpdateFeedbackSourceWithMappingsAction)
  .action(
    withAuditLogging("updated", "feedbackSource", async ({ ctx, parsedInput }) => {
      ctx.auditLoggingCtx.feedbackSourceId = parsedInput.feedbackSourceId;
      ctx.auditLoggingCtx.workspaceId = parsedInput.workspaceId;
      await applyRateLimit(rateLimitConfigs.actions.feedbackSourceMutation, ctx.user.id);

      const organizationId = await getOrganizationIdFromFeedbackSourceId(parsedInput.feedbackSourceId);
      ctx.auditLoggingCtx.organizationId = organizationId;
      await assertCan({ type: "user", id: ctx.user.id }, "workspace.write", {
        type: "workspace",
        id: parsedInput.workspaceId,
      });

      // The check above proves the caller may act in `workspaceId`; it does not prove this feedback
      // source lives there, and the organization it was authorized against came from the source
      // rather than the workspace. Pin the two together up front so every branch below — and the
      // mappings resolved against the same workspace — operates on one tenant, and so a mismatch
      // fails here rather than as a Prisma error from the update.
      const feedbackSource = await prisma.feedbackSource.findUnique({
        where: { id: parsedInput.feedbackSourceId, workspaceId: parsedInput.workspaceId },
        select: {
          feedbackDirectoryId: true,
          formbricksMappings: { select: { surveyId: true } },
          type: true,
        },
      });
      if (!feedbackSource) {
        throw new ResourceNotFoundError("FeedbackSource", parsedInput.feedbackSourceId);
      }
      await assertFeedbackSourceDirectoryAccess(
        ctx.user.id,
        feedbackSource.feedbackDirectoryId,
        parsedInput.workspaceId,
        "write"
      );

      let mappingsInput: TMappingsInput | undefined;

      if (parsedInput.formbricksMappings?.length) {
        mappingsInput = await resolveFormbricksMappingsInput(
          parsedInput.formbricksMappings,
          parsedInput.workspaceId,
          feedbackSource.formbricksMappings.map(({ surveyId }) => surveyId)
        );
      } else if (parsedInput.fieldMappings && parsedInput.fieldMappings.length > 0) {
        mappingsInput = {
          type: "field",
          mappings:
            feedbackSource.type === "csv"
              ? sanitizeAndValidateCsvFieldMappings(parsedInput.fieldMappings)
              : parsedInput.fieldMappings,
        };
      }

      const updatedFeedbackSource = await updateFeedbackSourceWithMappings(
        parsedInput.feedbackSourceId,
        parsedInput.workspaceId,
        parsedInput.feedbackSourceInput,
        mappingsInput
      );
      ctx.auditLoggingCtx.oldObject = feedbackSource;
      ctx.auditLoggingCtx.newObject = updatedFeedbackSource;
      return updatedFeedbackSource;
    })
  );

const ZGetResponseCountAction = z.object({
  surveyId: ZId,
  workspaceId: ZId,
});

export const getResponseCountAction = authenticatedActionClient
  .inputSchema(ZGetResponseCountAction)
  .action(
    async ({
      ctx,
      parsedInput,
    }: {
      ctx: AuthenticatedActionClientCtx;
      parsedInput: z.infer<typeof ZGetResponseCountAction>;
    }): Promise<number> => {
      // Authorize against the survey's own workspace, not the caller-supplied one: the workspaceTeam
      // check only proves team access to whatever workspace the caller names, so passing a workspace
      // they do have access to would otherwise return the response count for any survey in the org.
      const surveyWorkspaceId = await getWorkspaceIdFromSurveyId(parsedInput.surveyId);

      await assertCan({ type: "user", id: ctx.user.id }, "workspace.write", {
        type: "workspace",
        id: surveyWorkspaceId,
      });
      // ENG-3282: a restricted survey's response count is its owner's and the administrators'.
      await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
        type: "survey",
        id: parsedInput.surveyId,
      });

      return getResponseCountBySurveyId(parsedInput.surveyId);
    }
  );

const ZImportHistoricalResponsesAction = z.object({
  feedbackSourceId: ZId,
  workspaceId: ZId,
  surveyId: ZId,
});

export const importHistoricalResponsesAction = authenticatedActionClient
  .inputSchema(ZImportHistoricalResponsesAction)
  .action(
    withAuditLogging("updated", "feedbackSource", async ({ ctx, parsedInput }) => {
      ctx.auditLoggingCtx.feedbackSourceId = parsedInput.feedbackSourceId;
      ctx.auditLoggingCtx.workspaceId = parsedInput.workspaceId;
      await applyRateLimit(rateLimitConfigs.actions.historicalResponseImport, ctx.user.id);

      const organizationId = await getOrganizationIdFromFeedbackSourceId(parsedInput.feedbackSourceId);
      ctx.auditLoggingCtx.organizationId = organizationId;
      await assertCan({ type: "user", id: ctx.user.id }, "workspace.write", {
        type: "workspace",
        id: parsedInput.workspaceId,
      });

      const feedbackSource = await getFeedbackSourceWithMappingsById(
        parsedInput.feedbackSourceId,
        parsedInput.workspaceId
      );
      if (!feedbackSource) {
        throw new ResourceNotFoundError("FeedbackSource", parsedInput.feedbackSourceId);
      }
      await assertFeedbackSourceDirectoryAccess(
        ctx.user.id,
        feedbackSource.feedbackDirectoryId,
        parsedInput.workspaceId,
        "write"
      );

      const survey = await getSurvey(parsedInput.surveyId);
      if (!survey) {
        throw new ResourceNotFoundError("Survey", parsedInput.surveyId);
      }

      // The authorization above covers the feedback source's workspace, not this survey — and the
      // import reads every response of `surveyId` and copies them into the source's feedback
      // directory. Without this check any caller with readWrite on one workspace could name a survey
      // from another organization and exfiltrate its responses into their own directory. Survey ids
      // are public (they appear in `/s/<surveyId>` links), so the id is not a secret. The picker only
      // ever offers surveys from this workspace (`getSurveysForUnifyAction` → `getSurveys(workspaceId)`).
      if (survey.workspaceId !== parsedInput.workspaceId) {
        throw new ResourceNotFoundError("Survey", parsedInput.surveyId);
      }
      // ENG-3282: the import copies this survey's responses, so the caller must be able to read them.
      await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
        type: "survey",
        id: survey.id,
      });
      // Copying responses into a feedback directory is outbound (ENG-3283): a restricted survey's
      // responses must not leave its access list this way either.
      await assertNewlyAttachedSurveysWorkspaceVisible([survey.id]);

      const importResult = await importHistoricalResponses(feedbackSource, survey);
      ctx.auditLoggingCtx.newObject = importResult;
      return importResult;
    })
  );

const ZGetFeedbackRecordContactsAction = z.object({
  workspaceId: ZId,
  userIds: z.array(z.string()).max(1000),
});

// Resolves a page of feedback records' user_ids to Formbricks contact ids (batched, deduped).
export const getFeedbackRecordContactsAction = authenticatedActionClient
  .inputSchema(ZGetFeedbackRecordContactsAction)
  .action(
    async ({
      ctx,
      parsedInput,
    }: {
      ctx: AuthenticatedActionClientCtx;
      parsedInput: z.infer<typeof ZGetFeedbackRecordContactsAction>;
    }): Promise<Record<string, string>> => {
      await assertCan({ type: "user", id: ctx.user.id }, "workspace.read", {
        type: "workspace",
        id: parsedInput.workspaceId,
      });

      return getContactIdsByUserIds(parsedInput.workspaceId, parsedInput.userIds);
    }
  );
