"use server";

import { z } from "zod";
import { ZId } from "@formbricks/types/common";
import { ZResponseFilterCriteria } from "@formbricks/types/responses";
import { assertCan } from "@/lib/authorization";
import { getDisplaysBySurveyIdWithContact } from "@/lib/display/service";
import { getResponseCountBySurveyId, getResponses } from "@/lib/response/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { getSurveySummary } from "./summary/lib/surveySummary";

const ZGetResponsesAction = z.object({
  surveyId: ZId,
  limit: z.number().optional(),
  offset: z.number().optional(),
  filterCriteria: ZResponseFilterCriteria.optional(),
});

export const getResponsesAction = authenticatedActionClient
  .inputSchema(ZGetResponsesAction)
  .action(async ({ ctx, parsedInput }) => {
    await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
      type: "survey",
      id: parsedInput.surveyId,
    });

    return getResponses(
      parsedInput.surveyId,
      parsedInput.limit,
      parsedInput.offset,
      parsedInput.filterCriteria,
      undefined,
      // The response cards on this page mark what each respondent was not shown (ENG-6936).
      { withNotShown: true }
    );
  });

const ZGetSurveySummaryAction = z.object({
  surveyId: ZId,
  filterCriteria: ZResponseFilterCriteria.optional(),
});

export const getSurveySummaryAction = authenticatedActionClient
  .inputSchema(ZGetSurveySummaryAction)
  .action(async ({ ctx, parsedInput }) => {
    await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
      type: "survey",
      id: parsedInput.surveyId,
    });
    return getSurveySummary(parsedInput.surveyId, parsedInput.filterCriteria);
  });

const ZGetResponseCountAction = z.object({
  surveyId: ZId,
  filterCriteria: ZResponseFilterCriteria.optional(),
});

export const getResponseCountAction = authenticatedActionClient
  .inputSchema(ZGetResponseCountAction)
  .action(async ({ ctx, parsedInput }) => {
    await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
      type: "survey",
      id: parsedInput.surveyId,
    });

    return getResponseCountBySurveyId(parsedInput.surveyId, parsedInput.filterCriteria);
  });

const ZGetDisplaysWithContactAction = z.object({
  surveyId: ZId,
  limit: z.int().min(1).max(100),
  offset: z.int().nonnegative(),
});

export const getDisplaysWithContactAction = authenticatedActionClient
  .inputSchema(ZGetDisplaysWithContactAction)
  .action(async ({ ctx, parsedInput }) => {
    await assertCan({ type: "user", id: ctx.user.id }, "survey.response_read", {
      type: "survey",
      id: parsedInput.surveyId,
    });

    return getDisplaysBySurveyIdWithContact(parsedInput.surveyId, parsedInput.limit, parsedInput.offset);
  });
