import { handleErrorResponse } from "@/app/api/v1/auth";
import { responses } from "@/app/lib/api/response";
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { can } from "@/lib/authorization";
import { getWorkspaceAuthorizationActionForMethod } from "@/lib/authorization/permission-action";
import { getPublicDomain } from "@/lib/getPublicUrl";
import { getSurvey } from "@/lib/survey/service";
import { SURVEY_ACTION_FOR_METHOD, canApiKeyReachSurveyResource } from "@/lib/survey/visibility/api-key";
import { generateSurveySingleUseLinkParamsList } from "@/lib/utils/single-use-surveys";

export const GET = withV1ApiWrapper({
  handler: async ({
    req,
    props,
    authentication,
  }: THandlerParams<{ params: Promise<{ surveyId: string }> }>) => {
    if (!authentication || !("apiKeyId" in authentication)) {
      return { response: responses.notAuthenticatedResponse() };
    }

    try {
      const params = await props.params;
      const survey = await getSurvey(params.surveyId);
      if (!survey) {
        return {
          response: responses.notFoundResponse("Survey", params.surveyId),
        };
      }
      // Checked at write level despite being a GET: this endpoint *mints* credentials rather than
      // reading anything. Each returned link carries a fresh HMAC-signed suId/suToken pair that the
      // unauthenticated POST /api/v1/client/{workspaceId}/responses accepts, so at "read" a
      // reporting-only key — the level you would hand an external analyst or BI tool — could generate
      // thousands of valid submission links and inject responses with them.
      if (
        !(await can(
          { type: "apiKey", id: authentication.apiKeyId },
          getWorkspaceAuthorizationActionForMethod("POST"),
          { type: "workspace", id: survey.workspaceId }
        )) ||
        // ENG-3282: the minted links write responses into this survey, so a restricted one is out of the
        // key's reach, at the same level as a response write.
        !(await canApiKeyReachSurveyResource(authentication.apiKeyId, SURVEY_ACTION_FOR_METHOD.POST, {
          type: "survey",
          id: survey.id,
        }))
      ) {
        return {
          response: responses.unauthorizedResponse(),
        };
      }

      if (survey.type !== "link") {
        return {
          response: responses.badRequestResponse("Single use links are only available for link surveys"),
        };
      }

      if (!survey.singleUse || !survey.singleUse.enabled) {
        return {
          response: responses.badRequestResponse("Single use links are not enabled for this survey"),
        };
      }
      const searchParams = req.nextUrl.searchParams;
      const limit = searchParams.get("limit") ? Number(searchParams.get("limit")) : 10;

      if (limit < 1) {
        return {
          response: responses.badRequestResponse("Limit cannot be less than 1"),
        };
      }

      if (limit > 5000) {
        return {
          response: responses.badRequestResponse("Limit cannot be more than 5000"),
        };
      }

      const singleUseLinkParams = generateSurveySingleUseLinkParamsList(
        limit,
        survey.id,
        survey.singleUse.isEncrypted
      );

      const publicDomain = getPublicDomain();
      // map single use ids to survey links
      const surveyLinks = singleUseLinkParams.map(({ suId, suToken }) => {
        const surveyLink = new URL(`${publicDomain}/s/${survey.id}`);
        surveyLink.searchParams.set("suId", suId);
        if (suToken) {
          surveyLink.searchParams.set("suToken", suToken);
        }
        return surveyLink.toString();
      });

      return {
        response: responses.successResponse(surveyLinks),
      };
    } catch (error) {
      return handleErrorResponse(error);
    }
  },
});
