import type {
  TCreateWorkflowInput,
  TListWorkflowRunsInput,
  TListWorkflowsInput,
  TWorkflowSortBy,
} from "../contracts";
import { WorkflowConflictError, isUniqueConstraintViolation } from "../errors";
import {
  type TWorkflowListCursor,
  buildNextWorkflowListCursor,
  decodeWorkflowListCursor,
  encodeWorkflowListCursor,
} from "../handlers/cursor";
import {
  type TWorkflowRunListCursor,
  buildNextWorkflowRunListCursor,
  decodeWorkflowRunListCursor,
  encodeWorkflowRunListCursor,
} from "../handlers/runs-cursor";
import type { TWorkflowStatus } from "../types/common";
import type { TWorkflowDefinition, TWorkflowExecutableDefinition } from "../types/document";
import type { TWorkflowTriggerRunPayload } from "../types/runs";
import {
  type TWorkflowSampleData,
  WORKFLOW_SAMPLE_LAST_CALL_SOURCE,
  WORKFLOW_SAMPLE_TRIGGER_SOURCE,
} from "../types/samples";
import { WORKFLOW_TRIGGERS } from "../types/triggers/enum";
import type {
  LastRunInclude,
  WebhookTokenIssuer,
  WorkflowDelegate,
  WorkflowOrderByInput,
  WorkflowRow,
  WorkflowRowWithLastRun,
  WorkflowRunListRow,
  WorkflowRunWhereInput,
  WorkflowRunWithLogsRow,
  WorkflowSampleRow,
  WorkflowWhereInput,
  WorkflowsDb,
} from "./ports";

/** Identifies one workflow within its workspace, for composite-key (`id`, `workspaceId`) scoping. */
export interface WorkflowScopedParams {
  workflowId: string;
  workspaceId: string;
}

/** Fields a patch may persist. `status` is changed only through the lifecycle methods, never here. */
export interface WorkflowUpdateInput {
  name?: string;
  description?: string | null;
  definition?: TWorkflowDefinition;
  /** Issue a Webhook Secret URL token with this write: the first save of a Webhook trigger. */
  issueWebhookToken?: boolean;
}

/**
 * Eagerly load the most recent run, the creating user's name and the origin each stored secret header
 * value was set for, so the serializer can emit `lastRun`, `creator` and each secret's `boundOrigin`
 * without an N+1. Every resource-returning path uses this include.
 */
const LAST_RUN_INCLUDE: LastRunInclude = {
  runs: { take: 1, orderBy: { createdAt: "desc" } },
  creator: { select: { name: true } },
  // The Runs column counts real runs only, like the runs list's default and billing: Test runs are excluded.
  _count: { select: { runs: { where: { isDryRun: false } } } },
  secrets: { select: { id: true, boundOrigin: true } },
};

/** Every field a workflow update may set; mirrors the injected delegate's `update` data shape. */
type WorkflowUpdateData = Parameters<WorkflowDelegate["update"]>[0]["data"];

/**
 * Single place that issues a workspace-scoped `workflow.update` with the standard last-run include.
 * The delegate is passed explicitly so it serves both the base client and an interactive transaction.
 */
const updateWorkflowRow = (
  workflow: WorkflowDelegate,
  { workflowId, workspaceId }: WorkflowScopedParams,
  data: WorkflowUpdateData
): Promise<WorkflowRowWithLastRun> =>
  workflow.update({
    where: { id_workspaceId: { id: workflowId, workspaceId } },
    data,
    include: LAST_RUN_INCLUDE,
  });

// Bound on copy-name retries in `duplicateWorkflow`; high enough to never hit in practice, low
// enough to fail fast instead of looping forever against a pathological set of taken names.
const MAX_DUPLICATE_NAME_ATTEMPTS = 50;

const buildCopyName = (baseName: string, attempt: number): string =>
  attempt === 1 ? `${baseName} (copy)` : `${baseName} (copy ${attempt.toString()})`;

const getOrderBy = (sortBy: TWorkflowSortBy): WorkflowOrderByInput[] => {
  switch (sortBy) {
    case "name":
      return [{ name: "asc" }, { id: "asc" }];
    case "createdAt":
      return [{ createdAt: "desc" }, { id: "desc" }];
    case "updatedAt":
    default:
      return [{ updatedAt: "desc" }, { id: "desc" }];
  }
};

const buildCursorWhere = (cursor: TWorkflowListCursor): WorkflowWhereInput => {
  if (cursor.sortBy === "name") {
    return {
      OR: [{ name: { gt: cursor.value } }, { name: cursor.value, id: { gt: cursor.id } }],
    };
  }

  // createdAt / updatedAt sort descending → page towards older rows.
  const value = new Date(cursor.value);
  if (cursor.sortBy === "createdAt") {
    return { OR: [{ createdAt: { lt: value } }, { createdAt: value, id: { lt: cursor.id } }] };
  }
  return { OR: [{ updatedAt: { lt: value } }, { updatedAt: value, id: { lt: cursor.id } }] };
};

const buildListWhere = (
  input: TListWorkflowsInput,
  cursor: TWorkflowListCursor | null
): WorkflowWhereInput => ({
  workspaceId: input.workspaceId,
  // Default-exclude archived workflows unless the caller explicitly filters on status.
  ...(input.statusIn ? { status: { in: input.statusIn } } : { status: { not: "archived" } }),
  ...(input.nameContains ? { name: { contains: input.nameContains, mode: "insensitive" } } : {}),
  ...(cursor ? buildCursorWhere(cursor) : {}),
});

export interface WorkflowListPage {
  workflows: WorkflowRowWithLastRun[];
  nextCursor: string | null;
  /** Workflows matching the filters across all pages; null unless `includeTotalCount` was requested. */
  totalCount: number | null;
}

/** Eager-load shape for a run's step logs, ordered by sequence; mirrors the injected delegate. */
const RUN_LOG_INCLUDE = {
  logs: { orderBy: { sequence: "asc" } },
  workflowVersion: { select: { version: true } },
} as const;

/** Keyset page for newest-first run listing (`createdAt desc`, `id desc` tie-breaker). */
const buildRunCursorWhere = (cursor: TWorkflowRunListCursor): WorkflowRunWhereInput => {
  const value = new Date(cursor.value);
  return { OR: [{ createdAt: { lt: value } }, { createdAt: value, id: { lt: cursor.id } }] };
};

/**
 * Leaves out runs of surveys the caller may not read (ENG-3282). Spelled as `surveyId IS NULL OR NOT IN`
 * because SQL's `NOT IN` alone also drops the rows whose `surveyId` is null. Nested under `AND` so it
 * never collides with the cursor's own `OR`.
 */
const buildRunSurveyExclusionWhere = (excludeSurveyIds: ReadonlyArray<string>): WorkflowRunWhereInput =>
  excludeSurveyIds.length === 0
    ? {}
    : { AND: [{ OR: [{ surveyId: null }, { surveyId: { notIn: [...excludeSurveyIds] } }] }] };

const buildRunListWhere = (
  input: TListWorkflowRunsServiceInput,
  cursor: TWorkflowRunListCursor | null
): WorkflowRunWhereInput => ({
  workspaceId: input.workspaceId,
  ...(input.workflowId ? { workflowId: input.workflowId } : {}),
  ...(input.responseId ? { responseId: input.responseId } : {}),
  ...(input.statusIn ? { status: { in: input.statusIn } } : {}),
  ...(input.triggerTypeIn ? { triggerType: { in: input.triggerTypeIn } } : {}),
  ...(input.isDryRun !== undefined ? { isDryRun: input.isDryRun } : {}),
  ...(cursor ? buildRunCursorWhere(cursor) : {}),
  ...buildRunSurveyExclusionWhere(input.excludeSurveyIds ?? []),
});

/** The list query plus the surveys whose runs the caller may not read (see `listUnreadableSurveyIds`). */
export type TListWorkflowRunsServiceInput = TListWorkflowRunsInput & {
  excludeSurveyIds?: ReadonlyArray<string>;
};

export interface WorkflowRunListPage {
  runs: WorkflowRunListRow[];
  nextCursor: string | null;
}

export interface WorkflowsService {
  listWorkflows: (input: TListWorkflowsInput) => Promise<WorkflowListPage>;
  createWorkflow: (
    input: TCreateWorkflowInput,
    options: { createdBy: string | null }
  ) => Promise<WorkflowRowWithLastRun>;
  getWorkflowById: (workflowId: string) => Promise<WorkflowRowWithLastRun | null>;
  updateWorkflow: (
    params: WorkflowScopedParams,
    data: WorkflowUpdateInput
  ) => Promise<WorkflowRowWithLastRun>;
  duplicateWorkflow: (
    source: WorkflowRowWithLastRun,
    options: { name?: string; createdBy: string | null }
  ) => Promise<WorkflowRowWithLastRun>;
  deleteWorkflow: (params: WorkflowScopedParams) => Promise<void>;
  setStatus: (params: WorkflowScopedParams, status: TWorkflowStatus) => Promise<WorkflowRowWithLastRun>;
  enableWorkflow: (
    params: WorkflowScopedParams,
    options: { definition: TWorkflowExecutableDefinition; publishedBy: string | null }
  ) => Promise<WorkflowRowWithLastRun>;
  disableWorkflow: (params: WorkflowScopedParams) => Promise<WorkflowRowWithLastRun>;
  listWorkflowRuns: (input: TListWorkflowRunsServiceInput) => Promise<WorkflowRunListPage>;
  getWorkflowRun: (runId: string) => Promise<WorkflowRunWithLogsRow | null>;
  regenerateWebhookToken: (params: WorkflowScopedParams) => Promise<WorkflowRowWithLastRun>;
  revealWebhookToken: (row: WorkflowRow) => string | null;
  /** The Webhook trigger's expected payload, set by editors only (ADR 0052). */
  getTriggerSample: (workflowId: string) => Promise<WorkflowSampleRow | null>;
  /** The last payload a call to the Secret URL sent, with its time and IP. */
  getLastCall: (workflowId: string) => Promise<WorkflowSampleRow | null>;
  setTriggerSample: (params: WorkflowScopedParams, sample: TWorkflowSampleData) => Promise<WorkflowSampleRow>;
  /**
   * Saves a Test run as a queued dry run with no version, keeping the draft `definition` it executes;
   * the adapter then runs it (ENG-7181).
   */
  createTestRun: (
    params: WorkflowScopedParams,
    run: { triggerPayload: TWorkflowTriggerRunPayload; definition: TWorkflowExecutableDefinition }
  ) => Promise<{ id: string }>;
}

/** Token columns for a newly issued Webhook Secret URL token. */
const issueWebhookTokenColumns = (
  webhookTokens: WebhookTokenIssuer
): { webhookTokenHash: string; webhookTokenEncrypted: string } => {
  const { hash, encrypted } = webhookTokens.issue();
  return { webhookTokenHash: hash, webhookTokenEncrypted: encrypted };
};

const hasWebhookTrigger = (definition: TWorkflowDefinition): boolean =>
  definition.trigger?.triggerType === WORKFLOW_TRIGGERS.WEBHOOK;

const triggerSampleKey = (workflowId: string) => ({
  workflowId_source: { workflowId, source: WORKFLOW_SAMPLE_TRIGGER_SOURCE },
});

const lastCallKey = (workflowId: string) => ({
  workflowId_source: { workflowId, source: WORKFLOW_SAMPLE_LAST_CALL_SOURCE },
});

/**
 * Data-access layer for the v3 Workflows API. Prisma is injected (see `ports.ts`) so the package
 * carries no runtime dependency on `@formbricks/database`. Inputs are already validated by the
 * contract schemas at the handler boundary, so the service does not re-parse them. DB errors are
 * allowed to bubble to the handler's error mapper (logged there once, as a 500).
 */
export const createWorkflowsService = ({
  prisma,
  webhookTokens,
}: {
  prisma: WorkflowsDb;
  webhookTokens: WebhookTokenIssuer;
}): WorkflowsService => ({
  async listWorkflows(input) {
    const cursor = input.cursor ? decodeWorkflowListCursor(input.cursor, input.sortBy) : null;

    // The count runs beside the page, over the same filters minus the cursor (never a skip).
    const [rows, totalCount] = await Promise.all([
      prisma.workflow.findMany({
        where: buildListWhere(input, cursor),
        orderBy: getOrderBy(input.sortBy),
        take: input.limit + 1,
        include: LAST_RUN_INCLUDE,
      }),
      input.includeTotalCount
        ? prisma.workflow.count({ where: buildListWhere(input, null) })
        : Promise.resolve(null),
    ]);

    const hasMore = rows.length > input.limit;
    const workflows = hasMore ? rows.slice(0, input.limit) : rows;
    const lastRow = workflows.at(-1);

    return {
      workflows,
      totalCount,
      nextCursor:
        hasMore && lastRow
          ? encodeWorkflowListCursor(buildNextWorkflowListCursor(lastRow, input.sortBy))
          : null,
    };
  },

  async createWorkflow(input, { createdBy }) {
    return prisma.workflow.create({
      data: {
        workspaceId: input.workspaceId,
        name: input.name,
        description: input.description ?? null,
        status: "draft",
        definition: input.definition,
        createdBy,
        // The token is created on the first save of a Webhook trigger (ENG-7177).
        ...(hasWebhookTrigger(input.definition) ? issueWebhookTokenColumns(webhookTokens) : {}),
      },
      include: LAST_RUN_INCLUDE,
    });
  },

  async getWorkflowById(workflowId) {
    return prisma.workflow.findUnique({
      where: { id: workflowId },
      include: LAST_RUN_INCLUDE,
    });
  },

  async updateWorkflow({ workflowId, workspaceId }, data) {
    return updateWorkflowRow(
      prisma.workflow,
      { workflowId, workspaceId },
      {
        ...(data.name !== undefined ? { name: data.name } : {}),
        ...(data.description !== undefined ? { description: data.description } : {}),
        ...(data.definition !== undefined ? { definition: data.definition } : {}),
        ...(data.issueWebhookToken ? issueWebhookTokenColumns(webhookTokens) : {}),
      }
    );
  },

  async duplicateWorkflow(source, { name, createdBy }) {
    const createCopy = (copyName: string): Promise<WorkflowRowWithLastRun> =>
      prisma.workflow.create({
        data: {
          workspaceId: source.workspaceId,
          name: copyName,
          description: source.description,
          status: "draft",
          definition: source.definition,
          createdBy,
          // A copy never shares the source's Secret URL: it gets a token of its own (ADR 0048).
          ...(hasWebhookTrigger(source.definition) ? issueWebhookTokenColumns(webhookTokens) : {}),
        },
        include: LAST_RUN_INCLUDE,
      });

    // A caller-supplied name is used verbatim (names are not unique; do not rename it).
    if (name !== undefined) {
      return createCopy(name);
    }

    // No name given: generate a "(copy)"-suffixed name. Names are no longer workspace-unique, so
    // the first attempt normally succeeds; the suffix-advance retry is kept as a cheap safety net
    // in case a unique constraint ever returns. Any non-P2002 error is a real failure → rethrow.
    for (let attempt = 1; attempt <= MAX_DUPLICATE_NAME_ATTEMPTS; attempt++) {
      try {
        return await createCopy(buildCopyName(source.name, attempt));
      } catch (error) {
        if (isUniqueConstraintViolation(error)) {
          continue;
        }
        throw error;
      }
    }

    throw new WorkflowConflictError("Could not find an available copy name for this workflow.");
  },

  async deleteWorkflow({ workflowId, workspaceId }) {
    // Hard delete; Prisma `onDelete: Cascade` removes the workflow's runs + run logs (GDPR).
    await prisma.workflow.delete({ where: { id_workspaceId: { id: workflowId, workspaceId } } });
  },

  async setStatus({ workflowId, workspaceId }, status) {
    return updateWorkflowRow(prisma.workflow, { workflowId, workspaceId }, { status });
  },

  async enableWorkflow({ workflowId, workspaceId }, { definition, publishedBy }) {
    // Enable atomically. The state guard lives INSIDE the transaction: a conditional updateMany flips
    // exactly one draft/disabled row to enabled. The row lock serializes concurrent enables, so a
    // request that lost the race reads `count: 0` and is rejected here — a workflow can never be
    // enabled twice (nor gain a duplicate version) by a check that passed before the transaction. The
    // version snapshot (version = max + 1) is written in the same transaction, so an enabled workflow
    // always has a live version. The executable `definition` is validated by the handler.
    try {
      return await prisma.$transaction(async (tx) => {
        const { count } = await tx.workflow.updateMany({
          where: { id: workflowId, workspaceId, status: { in: ["draft", "disabled"] } },
          data: { status: "enabled" },
        });
        if (count !== 1) {
          throw new WorkflowConflictError("The workflow is no longer in a state that can be enabled.");
        }

        const latest = await tx.workflowVersion.findFirst({
          where: { workflowId },
          orderBy: { version: "desc" },
          select: { version: true },
        });
        await tx.workflowVersion.create({
          data: { workflowId, workspaceId, version: (latest?.version ?? 0) + 1, definition, publishedBy },
        });

        const enabled = await tx.workflow.findUnique({
          where: { id: workflowId },
          include: LAST_RUN_INCLUDE,
        });
        if (!enabled) {
          throw new WorkflowConflictError("The workflow no longer exists.");
        }
        return enabled;
      });
    } catch (error) {
      // Belt-and-suspenders for the simultaneous case: if two transactions read the same max version
      // before either commits, the second `workflowVersion.create` violates @@unique([workflowId,
      // version]). The transaction has rolled back cleanly, so surface a retryable 409.
      if (isUniqueConstraintViolation(error)) {
        throw new WorkflowConflictError("The workflow was just enabled by another request. Please retry.");
      }
      throw error;
    }
  },

  async disableWorkflow({ workflowId, workspaceId }) {
    return updateWorkflowRow(prisma.workflow, { workflowId, workspaceId }, { status: "disabled" });
  },

  async listWorkflowRuns(input) {
    const cursor = input.cursor ? decodeWorkflowRunListCursor(input.cursor) : null;

    const rows = await prisma.workflowRun.findMany({
      where: buildRunListWhere(input, cursor),
      orderBy: [{ createdAt: "desc" }, { id: "desc" }],
      take: input.limit + 1,
      // List summaries never use these large JSON columns; skip them so PG doesn't read/ship
      // up to 100 big blobs per page. The detail `findUnique` still loads them.
      omit: { triggerPayload: true, data: true, testRunDefinition: true },
      // Join the workflow's name so the workspace-wide runs table can label rows without an N+1.
      include: { workflow: { select: { name: true } } },
    });

    const hasMore = rows.length > input.limit;
    const runs = hasMore ? rows.slice(0, input.limit) : rows;
    const lastRow = runs.at(-1);

    return {
      runs,
      nextCursor:
        hasMore && lastRow ? encodeWorkflowRunListCursor(buildNextWorkflowRunListCursor(lastRow)) : null,
    };
  },

  async getWorkflowRun(runId) {
    // Workspace scoping is enforced by the handler: it authorizes against the loaded run's
    // workspaceId (a cross-workspace runId surfaces as 403), mirroring getWorkflowById.
    return prisma.workflowRun.findUnique({ where: { id: runId }, include: RUN_LOG_INCLUDE });
  },

  async regenerateWebhookToken(params) {
    // Overwriting the hash is what kills the old URL: the next call with it no longer matches.
    return updateWorkflowRow(prisma.workflow, params, issueWebhookTokenColumns(webhookTokens));
  },

  revealWebhookToken(row) {
    return row.webhookTokenEncrypted ? webhookTokens.reveal(row.webhookTokenEncrypted) : null;
  },

  async getTriggerSample(workflowId) {
    return prisma.workflowSample.findUnique({ where: triggerSampleKey(workflowId) });
  },

  async getLastCall(workflowId) {
    return prisma.workflowSample.findUnique({ where: lastCallKey(workflowId) });
  },

  async setTriggerSample({ workflowId, workspaceId }, sample) {
    // Its own table, so a sample write never bumps `Workflow.updatedAt` (ADR 0048).
    return prisma.workflowSample.upsert({
      where: triggerSampleKey(workflowId),
      create: { workflowId, workspaceId, source: WORKFLOW_SAMPLE_TRIGGER_SOURCE, sample },
      update: { sample },
    });
  },

  async createTestRun({ workflowId, workspaceId }, { triggerPayload, definition }) {
    // No version and never dispatched: the adapter runs it in the request. `isDryRun` keeps it out of
    // billing, usage counts and the run reconcilers. A response run records its survey and response as
    // a real one does, so the runs list's survey visibility filter covers it too. The draft it runs is
    // kept on the row, as a version keeps a live run's, so the runner executes exactly this definition
    // and the Runs tab can draw it after the draft changes.
    const responseColumns =
      triggerPayload.type === WORKFLOW_TRIGGERS.RESPONSE_COMPLETED
        ? { surveyId: triggerPayload.surveyId, responseId: triggerPayload.responseId }
        : {};
    return prisma.workflowRun.create({
      data: {
        workflowId,
        workspaceId,
        workflowVersionId: null,
        status: "queued",
        triggerType: triggerPayload.type,
        ...responseColumns,
        isDryRun: true,
        attempt: 0,
        triggerPayload,
        testRunDefinition: definition,
      },
      select: { id: true },
    });
  },
});
