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";

const builtins = (params: { userType?: TailorAnyDBType }) => {
  const authorUserId = db.uuid().description("Foreign key to User who authored the comment");
  return {
    itemId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: pipelineItem },
        backward: "comments",
      })
      .description("ID of the item this comment is attached to"),
    authorUserId: params.userType
      ? authorUserId.relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "pipelineItemComments",
        })
      : authorUserId,
    body: db.string().description("Comment body"),
  };
};

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

export interface CreatePipelineItemCommentTypeParams<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 createPipelineItemCommentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePipelineItemCommentTypeParams<F>,
) {
  return db
    .type("PipelineItemComment", {
      ...builtins(params),
      // 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(
      "A user-posted comment on an item. Forms a chronological discussion thread; only the author can edit or delete their own comment.",
    )
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const pipelineItemComment = createPipelineItemCommentType({});
