import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { pipelineItem } from "./pipelineItem";
import { pipelineStage } from "./pipelineStage";

const builtins = (params: { userType?: TailorAnyDBType }) => {
  const movedByUserId = db.uuid().description("Foreign key to User who moved the item");
  return {
    itemId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: pipelineItem },
        backward: "transitions",
      })
      .description("ID of the item that was moved"),
    fromStageId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: pipelineStage },
        backward: "outgoingTransitions",
      })
      .description("ID of the source stage"),
    toStageId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: pipelineStage, as: "toStage" },
        backward: "incomingTransitions",
      })
      .description("ID of the destination stage"),
    movedByUserId: params.userType
      ? movedByUserId.relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "pipelineStageTransitions",
        })
      : movedByUserId,
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

export interface CreatePipelineStageTransitionTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: NoReservedFields<F, ReservedFields>;
  /** Related User type (user-management module). The instance wired by the consuming app is injected here. */
  userType?: TailorAnyDBType;
}

export function createPipelineStageTransitionType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePipelineStageTransitionTypeParams<F>,
) {
  return db
    .type("PipelineStageTransition", {
      ...builtins(params),
      // The standard `createdAt` timestamp doubles as the event time; rows are
      // immutable, so no separate moved-at field is needed (mirrors PipelineItemChange).
      // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- mirrors erp-kit's createXxxType factories; field bag is constrained but TS can't prove F is concrete
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .description(
      "PipelineStage transition history. An append-only audit log appended each time an item moves between stages.",
    )
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const pipelineStageTransition = createPipelineStageTransitionType({});
