import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { LabelNotAttachedError } from "../lib/errors.generated";

export interface DetachLabelFromPipelineItemInput {
  itemId: string;
  labelId: string;
}

export async function run(
  db: Transaction,
  input: DetachLabelFromPipelineItemInput,
  ctx: CommandContext,
) {
  const existing = await db
    .selectFrom("PipelineItemLabel")
    .selectAll()
    .where("itemId", "=", input.itemId)
    .where("labelId", "=", input.labelId)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new LabelNotAttachedError(input.labelId));
  }

  await db.deleteFrom("PipelineItemLabel").where("id", "=", existing.id).execute();

  const now = new Date();

  await db
    .insertInto("PipelineItemChange")
    .values({
      itemId: input.itemId,
      changedByUserId: ctx.actorId,
      changeType: "LABEL",
      fieldName: "LABEL",
      prevValue: input.labelId,
      newValue: null,
      createdAt: now,
      updatedAt: null,
    })
    .execute();

  return ok({ pipelineItemLabel: existing });
}
