import "server-only";
import { logger } from "@formbricks/logger";
import { queueV3AuditLog, skipV3AuditLog } from "@/app/api/v3/lib/audit";
import { getV3SessionUserId } from "@/app/api/v3/lib/auth";
import { capCustomCssIssues, customCssErrorsToInvalidParams } from "@/app/api/v3/lib/custom-css";
import { getV3CustomCssPrincipal } from "@/app/api/v3/lib/custom-css-rate-limit";
import { mapV3ThrownError } from "@/app/api/v3/lib/errors";
import {
  type InvalidParam,
  createdResponse,
  noContentResponse,
  problemBadRequest,
  problemConflict,
  problemCreativesNotEntitled,
  problemCustomCssInvalid,
  problemCustomCssPlanRequired,
  problemForbidden,
  problemUnprocessableContent,
  successListResponse,
  successResponse,
} from "@/app/api/v3/lib/response";
import type { TV3AuditLog, TV3Authentication } from "@/app/api/v3/lib/types";
import type { V3WorkspaceContext } from "@/app/api/v3/lib/workspace-context";
import { CustomCssInvalidError, CustomCssPlanRequiredError } from "@/modules/custom-css/lib/service";
import { getCreativesAccess } from "@/modules/ee/creatives/lib/access";
import {
  type TCreativesOperation,
  getCreativePatchOperation,
  isCreativesOperationAllowed,
} from "@/modules/ee/creatives/lib/access-rules";
import {
  type TAuthorizedCreative,
  type TCreativeAccess,
  authorizeCreative,
  authorizeCreativeWorkspace,
} from "@/modules/ee/creatives/lib/authorization";
import type { TCreativeState } from "@/modules/ee/creatives/lib/creative";
import { assertCreativeCustomCssWrite } from "@/modules/ee/creatives/lib/custom-css-write";
import { toPausedCreativeAuditEvents } from "@/modules/ee/creatives/lib/linked-creatives";
import {
  type TCreativeRecord,
  findCreativeRecord,
  findCreativeRecordsPage,
} from "@/modules/ee/creatives/lib/repository";
import {
  CreativeChangedError,
  CreativeInvalidError,
  type TCreativeChange,
  archiveCreative,
  assertCreativeEditable,
  createCreative,
  deleteCreative,
  duplicateCreative,
  pauseSurveyCreatives,
  restoreCreative,
  updateCreative,
} from "@/modules/ee/creatives/lib/service";
import { MAX_STATS_PAGES, buildCreativeStats, resolveStatsRange } from "@/modules/ee/creatives/lib/stats";
import {
  findCreativeDayDeviceCounts,
  findCreativePageCounts,
} from "@/modules/ee/creatives/lib/stats-repository";
import {
  applyCreativePatch,
  buildCreativeCreateState,
  validateCreativeState,
} from "@/modules/ee/creatives/lib/write-rules";
import { parseV3CreativesListQuery } from "./list-query";
import type {
  TV3CreateCreativeBody,
  TV3CreativeStatsQuery,
  TV3PatchCreativeBody,
  TV3PauseCreativesBody,
} from "./schemas";
import { type TV3CreativeResource, serializeV3Creative } from "./serializers";

/**
 * The v3 creative operations (ENG-3993): the layer the `/api/v3/creatives` routes and the creative MCP
 * tools both call. Each takes parsed input and the caller's authentication and returns a `Response`
 * (success, or RFC 9457 problem), so an MCP tool is a thin adapter over the same behaviour.
 *
 * Access goes through `authorizeWorkspaceOperation` / `authorizeCreativeOperation` only: the caller's
 * workspace permission first, then the instance's licence (ENG-6602). Writes validate the whole
 * resulting state with `validateCreativeState` (422 on a semantic problem) before the service checks the
 * references only the database can answer, inside the write's transaction.
 */

type TOperationContext = {
  authentication: TV3Authentication;
  requestId: string;
  instance: string;
  auditLog?: TV3AuditLog;
};

type TCreativeOperationParams = TOperationContext & { creativeId: string };

/** Where a creative's own Custom CSS sits in the body; processor errors are named after it. */
const CUSTOM_CSS_FIELD = "styling.theme.customCss";

/**
 * The plan gate and the processor for the creative's own CSS (ENG-3998), before anything is written.
 * Throws what `mapWriteError` turns into the 403 or 422.
 */
const assertCustomCssWrite = (
  previous: TCreativeState | null,
  next: TCreativeState,
  organizationId: string,
  authentication: TV3Authentication
): Promise<void> =>
  assertCreativeCustomCssWrite({
    type: next.type,
    previous: previous?.styling.theme.customCss,
    next: next.styling.theme.customCss,
    organizationId,
    principal: getV3CustomCssPrincipal(authentication),
  });

const creativeLocation = (creativeId: string): string => `/api/v3/creatives/${creativeId}`;

const problemInvalidCreative = (
  requestId: string,
  instance: string,
  invalidParams: InvalidParam[]
): Response =>
  problemUnprocessableContent(requestId, "The creative failed validation", {
    invalid_params: invalidParams,
    instance,
  });

const problemCreativeChanged = (requestId: string, instance: string, error: CreativeChangedError) => {
  const currentUpdatedAt = error.currentUpdatedAt.toISOString();
  return problemConflict(
    requestId,
    `The creative changed since it was last read; updatedAt is now ${currentUpdatedAt}. Re-read the creative and retry.`,
    instance,
    { details: { expectedUpdatedAt: error.expectedUpdatedAt.toISOString(), currentUpdatedAt } }
  );
};

const recordAudit = (
  auditLog: TV3AuditLog | undefined,
  organizationId: string,
  targetId: string,
  objects: { oldObject?: TV3CreativeResource; newObject?: TV3CreativeResource }
): void => {
  if (!auditLog) return;
  auditLog.organizationId = organizationId;
  auditLog.targetId = targetId;
  if (objects.oldObject !== undefined) auditLog.oldObject = objects.oldObject;
  if (objects.newObject !== undefined) auditLog.newObject = objects.newObject;
};

/** Audits a write to an existing creative as stored right before and after it; returns the result. */
const auditChange = (
  auditLog: TV3AuditLog | undefined,
  organizationId: string,
  { before, after }: TCreativeChange,
  now: Date
): TV3CreativeResource => {
  const resource = serializeV3Creative(after, now);
  recordAudit(auditLog, organizationId, after.id, {
    oldObject: serializeV3Creative(before, now),
    newObject: resource,
  });
  return resource;
};

const mapWriteError = (
  error: unknown,
  {
    log,
    requestId,
    instance,
    operation,
  }: { log: ReturnType<typeof logger.withContext>; requestId: string; instance: string; operation: string }
): Response => {
  if (error instanceof CreativeInvalidError) {
    log.warn({ statusCode: 422, invalidParams: error.invalidParams }, error.message);
    return problemInvalidCreative(requestId, instance, error.invalidParams);
  }
  if (error instanceof CreativeChangedError) {
    log.warn(
      {
        statusCode: 409,
        expectedUpdatedAt: error.expectedUpdatedAt.toISOString(),
        currentUpdatedAt: error.currentUpdatedAt.toISOString(),
      },
      "Creative precondition failed"
    );
    return problemCreativeChanged(requestId, instance, error);
  }
  if (error instanceof CustomCssPlanRequiredError) {
    log.warn({ statusCode: 403 }, "Creative custom CSS needs the plan");
    return problemCustomCssPlanRequired(requestId, error.message, instance);
  }
  if (error instanceof CustomCssInvalidError) {
    log.warn({ statusCode: 422 }, "Creative custom CSS failed validation");
    return problemCustomCssInvalid(requestId, {
      invalid_params: customCssErrorsToInvalidParams(error.errors, CUSTOM_CSS_FIELD),
      errors: capCustomCssIssues(error.errors),
      instance,
    });
  }
  return mapV3ThrownError(error, { log, requestId, instance, operation });
};

type TAuthorizeParams = Pick<TOperationContext, "authentication" | "requestId" | "instance">;

/** Reading creatives needs `read` on their workspace; everything else changes them and needs `readWrite`. */
const getMemberAccess = (operation: TCreativesOperation): TCreativeAccess =>
  operation === "list" || operation === "get" || operation === "stats" ? "read" : "readWrite";

/**
 * The licence gate (ENG-6602), applied once the caller's own access to the workspace is settled, so it
 * only ever speaks about a workspace the caller can see: `none` refuses every operation, `windDown` all
 * but listing, reading, pausing, closing and deleting (`isCreativesOperationAllowed`).
 */
const refuseUnentitledOperation = async (
  authorized: V3WorkspaceContext,
  operation: TCreativesOperation,
  { requestId, instance }: TAuthorizeParams
): Promise<Response | null> => {
  const access = await getCreativesAccess({
    organizationId: authorized.organizationId,
    workspaceId: authorized.workspaceId,
  });
  if (isCreativesOperationAllowed(access, operation)) return null;

  logger.withContext({ requestId }).warn({ statusCode: 403, access, operation }, "Creatives not entitled");
  return problemCreativesNotEntitled(requestId, { windDown: access === "windDown", instance });
};

/** May the caller run `operation` on a workspace's creatives as a whole (list, create)? */
const authorizeWorkspaceOperation = async (
  workspaceId: string,
  operation: TCreativesOperation,
  params: TAuthorizeParams
): Promise<Response | V3WorkspaceContext> => {
  const authorized = await authorizeCreativeWorkspace({
    ...params,
    workspaceId,
    access: getMemberAccess(operation),
  });
  if (authorized instanceof Response) return authorized;
  return (await refuseUnentitledOperation(authorized, operation, params)) ?? authorized;
};

/** May the caller run `operation` on one creative? The workspace is resolved from the creative. */
const authorizeCreativeOperation = async (
  creativeId: string,
  operation: TCreativesOperation,
  params: TAuthorizeParams
): Promise<Response | TAuthorizedCreative> => {
  const authorized = await authorizeCreative({ ...params, creativeId, access: getMemberAccess(operation) });
  if (authorized instanceof Response) return authorized;
  return (await refuseUnentitledOperation(authorized, operation, params)) ?? authorized;
};

/**
 * Authorizes the caller for `operation` on one creative and loads it, scoped by
 * `{ creativeId, workspaceId }`. A creative deleted in between answers the same 403 as an unknown one.
 */
const loadAuthorizedCreative = async (
  { creativeId, authentication, requestId, instance }: TCreativeOperationParams,
  operation: TCreativesOperation
): Promise<{ response: Response } | { record: TCreativeRecord; organizationId: string }> => {
  const authorized = await authorizeCreativeOperation(creativeId, operation, {
    authentication,
    requestId,
    instance,
  });
  if (authorized instanceof Response) return { response: authorized };

  const record = await findCreativeRecord(authorized.creativeId, authorized.workspaceId);
  if (!record) {
    return {
      response: problemForbidden(requestId, "You are not authorized to access this resource", instance),
    };
  }
  return { record, organizationId: authorized.organizationId };
};

export async function listV3Creatives({
  searchParams,
  authentication,
  requestId,
  instance,
}: Omit<TOperationContext, "auditLog"> & { searchParams: URLSearchParams }): Promise<Response> {
  const log = logger.withContext({ requestId });

  try {
    const parsed = parseV3CreativesListQuery(searchParams);
    if (!parsed.ok) {
      log.warn({ statusCode: 400, invalidParams: parsed.invalidParams }, "Validation failed");
      return problemBadRequest(requestId, "Invalid query parameters", {
        invalid_params: parsed.invalidParams,
        instance,
      });
    }
    const { query } = parsed;

    const authorized = await authorizeWorkspaceOperation(query.workspaceId, "list", {
      authentication,
      requestId,
      instance,
    });
    if (authorized instanceof Response) return authorized;

    const now = new Date();
    const rows = await findCreativeRecordsPage({
      workspaceId: authorized.workspaceId,
      sortBy: query.sortBy,
      after: query.after,
      take: query.limit + 1,
      name: query.name,
      types: query.types,
      surveyId: query.surveyId,
      displayStatuses: query.displayStatuses,
      now,
    });
    const page = rows.slice(0, query.limit);
    const last = page.at(-1);

    return successListResponse(
      page.map((record) => serializeV3Creative(record, now)),
      { limit: query.limit, nextCursor: rows.length > query.limit && last ? query.nextCursor(last) : null },
      { requestId }
    );
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: "creatives.list" });
  }
}

export async function createV3Creative({
  body,
  authentication,
  requestId,
  instance,
  auditLog,
}: TOperationContext & { body: TV3CreateCreativeBody }): Promise<Response> {
  const log = logger.withContext({ requestId, workspaceId: body.workspaceId });

  try {
    const authorized = await authorizeWorkspaceOperation(body.workspaceId, "create", {
      authentication,
      requestId,
      instance,
    });
    if (authorized instanceof Response) return authorized;

    const now = new Date();
    const state = buildCreativeCreateState(body, now);
    const problems = validateCreativeState(state);
    if (problems.length > 0) {
      log.warn({ statusCode: 422, invalidParams: problems }, "Creative failed validation");
      return problemInvalidCreative(requestId, instance, problems);
    }
    await assertCustomCssWrite(null, state, authorized.organizationId, authentication);

    const record = await createCreative({
      workspaceId: authorized.workspaceId,
      createdBy: getV3SessionUserId(authentication),
      state,
    });
    const resource = serializeV3Creative(record, now);
    recordAudit(auditLog, authorized.organizationId, record.id, { newObject: resource });

    return createdResponse(resource, {
      location: creativeLocation(record.id),
      requestId,
    });
  } catch (error) {
    return mapWriteError(error, { log, requestId, instance, operation: "creatives.create" });
  }
}

export async function getV3Creative(params: Omit<TCreativeOperationParams, "auditLog">): Promise<Response> {
  const { creativeId, requestId, instance } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    const loaded = await loadAuthorizedCreative(params, "get");
    if ("response" in loaded) return loaded.response;

    return successResponse(serializeV3Creative(loaded.record, new Date()), { requestId });
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: "creatives.get" });
  }
}

export async function patchV3Creative(
  params: TCreativeOperationParams & { body: TV3PatchCreativeBody }
): Promise<Response> {
  const { creativeId, body, requestId, instance, auditLog } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    // Pausing and closing (a body that sets only `status`) stay allowed in wind-down; any other change
    // needs the full licence.
    const loaded = await loadAuthorizedCreative(params, getCreativePatchOperation(body));
    if ("response" in loaded) return loaded.response;
    const { record, organizationId } = loaded;

    const now = new Date();
    const { expectedUpdatedAt, ...changes } = body;
    const precondition = expectedUpdatedAt === undefined ? undefined : new Date(expectedUpdatedAt);
    // An empty patch changes nothing, `updatedAt` included; its precondition and the archive still apply.
    if (Object.keys(changes).length === 0) {
      assertCreativeEditable(record, precondition);
      return successResponse(serializeV3Creative(record, now), { requestId });
    }

    // Planned inside the write, from the creative as stored then (see `updateCreative`).
    const plan = async (previous: TCreativeState): Promise<TCreativeState> => {
      const planned = applyCreativePatch(previous, changes, now);
      const problems = planned.ok ? validateCreativeState(planned.state, previous) : planned.invalidParams;
      if (!planned.ok || problems.length > 0) throw new CreativeInvalidError(problems);
      await assertCustomCssWrite(previous, planned.state, organizationId, params.authentication);
      return planned.state;
    };
    const change = await updateCreative({
      creativeId: record.id,
      workspaceId: record.workspaceId,
      expectedUpdatedAt: precondition,
      surveyIdToLink: changes.destination?.type === "survey" ? changes.destination.surveyId : null,
      plan,
    });

    return successResponse(auditChange(auditLog, organizationId, change, now), { requestId });
  } catch (error) {
    return mapWriteError(error, { log, requestId, instance, operation: "creatives.patch" });
  }
}

export async function deleteV3Creative(params: TCreativeOperationParams): Promise<Response> {
  const { creativeId, requestId, instance, auditLog } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    const loaded = await loadAuthorizedCreative(params, "delete");
    if ("response" in loaded) return loaded.response;
    const { record, organizationId } = loaded;

    recordAudit(auditLog, organizationId, record.id, { oldObject: serializeV3Creative(record, new Date()) });
    await deleteCreative(record.id, record.workspaceId);

    return noContentResponse({ requestId });
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: "creatives.delete" });
  }
}

/**
 * Pauses every In progress creative a survey opens, in one request: keeping a resumed survey's creatives
 * paused must work for any number of them, and one PATCH each would run into the 100 requests a minute
 * the API allows. Access is pausing one creative's: `readWrite` on the workspace, then the licence's
 * `pause` (allowed in wind-down). The workspace is supplied, as for a create, and the survey is looked up
 * within it, so an unknown survey or one in another workspace answers the same 403 as an unknown id.
 *
 * Audited like the survey-side unlinks: one entry per paused creative, by the same caller, and none for
 * the request itself, which has no one target.
 */
export async function pauseV3SurveyCreatives({
  body,
  authentication,
  requestId,
  instance,
  auditLog,
}: TOperationContext & { body: TV3PauseCreativesBody }): Promise<Response> {
  const log = logger.withContext({ requestId, workspaceId: body.workspaceId, surveyId: body.surveyId });

  try {
    const authorized = await authorizeWorkspaceOperation(body.workspaceId, "pause", {
      authentication,
      requestId,
      instance,
    });
    if (authorized instanceof Response) return authorized;

    const creativeIds = await pauseSurveyCreatives(body.surveyId, authorized.workspaceId, new Date());
    if (!creativeIds) {
      log.warn({ statusCode: 403 }, "Survey not found in the workspace");
      return problemForbidden(requestId, "You are not authorized to access this resource", instance);
    }

    if (auditLog) {
      const actor = { ...auditLog, organizationId: authorized.organizationId };
      const events = toPausedCreativeAuditEvents(actor, creativeIds);
      await Promise.all(events.map((event) => queueV3AuditLog(event, requestId, log)));
      skipV3AuditLog(auditLog);
    }

    return successResponse({ paused: creativeIds.length, creativeIds }, { requestId });
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: "creatives.pause" });
  }
}

/** Archive and restore: authorize, run the lifecycle change, audit before and after, return the resource. */
const runLifecycleOperation = async (
  params: TCreativeOperationParams,
  operation: "archive" | "restore",
  mutate: (record: TCreativeRecord, now: Date) => Promise<TCreativeChange>
): Promise<Response> => {
  const { creativeId, requestId, instance, auditLog } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    const loaded = await loadAuthorizedCreative(params, operation);
    if ("response" in loaded) return loaded.response;
    const { record, organizationId } = loaded;

    const now = new Date();
    const change = await mutate(record, now);
    return successResponse(auditChange(auditLog, organizationId, change, now), { requestId });
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: `creatives.${operation}` });
  }
};

// Each reads the creative again under its row lock: `record` only names it (and the survey to lock).
export const archiveV3Creative = (params: TCreativeOperationParams): Promise<Response> =>
  runLifecycleOperation(params, "archive", (record, now) =>
    archiveCreative(record.id, record.workspaceId, now)
  );

export const restoreV3Creative = (params: TCreativeOperationParams): Promise<Response> =>
  runLifecycleOperation(params, "restore", (record) =>
    restoreCreative(record.id, record.workspaceId, record.surveyId)
  );

export async function duplicateV3Creative(params: TCreativeOperationParams): Promise<Response> {
  const { creativeId, authentication, requestId, instance, auditLog } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    const loaded = await loadAuthorizedCreative(params, "duplicate");
    if ("response" in loaded) return loaded.response;
    const { record, organizationId } = loaded;

    const copy = await duplicateCreative({ record, createdBy: getV3SessionUserId(authentication) });
    const resource = serializeV3Creative(copy, new Date());
    recordAudit(auditLog, organizationId, copy.id, { newObject: resource });

    return createdResponse(resource, {
      location: creativeLocation(copy.id),
      requestId,
    });
  } catch (error) {
    return mapWriteError(error, { log, requestId, instance, operation: "creatives.duplicate" });
  }
}

/**
 * A creative's Impressions and Clicks per UTC day, from the rollups the counter flush writes
 * (ENG-4000). Read access, like `getV3Creative`; archived creatives keep their counts.
 */
export async function getV3CreativeStats(
  params: Omit<TCreativeOperationParams, "auditLog"> & { query: TV3CreativeStatsQuery }
): Promise<Response> {
  const { creativeId, query, authentication, requestId, instance } = params;
  const log = logger.withContext({ requestId, creativeId });

  try {
    const authorized = await authorizeCreativeOperation(creativeId, "stats", {
      authentication,
      requestId,
      instance,
    });
    if (authorized instanceof Response) return authorized;

    const resolved = resolveStatsRange(query, new Date());
    if (!resolved.ok) {
      return problemBadRequest(requestId, "Invalid query parameters", {
        invalid_params: [resolved.invalidParam],
        instance,
      });
    }

    const { range } = resolved;
    const groupBy = query.groupBy ?? null;
    const { workspaceId } = authorized;
    const [dayDeviceCounts, pageCounts] = await Promise.all([
      findCreativeDayDeviceCounts(creativeId, workspaceId, range.from, range.to),
      groupBy === "page"
        ? findCreativePageCounts(creativeId, workspaceId, range.from, range.to, MAX_STATS_PAGES)
        : [],
    ]);

    return successResponse(buildCreativeStats({ creativeId, range, groupBy, dayDeviceCounts, pageCounts }), {
      requestId,
    });
  } catch (error) {
    return mapV3ThrownError(error, { log, requestId, instance, operation: "creatives.stats" });
  }
}
