import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { pipelineItemLifecycle } from "../db/pipelineItem.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { ItemNotClosedError, ItemNotFoundError } from "../lib/errors.generated";

export interface ReopenPipelineItemInput {
  itemId: string;
}

export async function run(db: Transaction, input: ReopenPipelineItemInput, ctx: CommandContext) {
  const item = await db
    .selectFrom("PipelineItem")
    .selectAll()
    .where("id", "=", input.itemId)
    .forUpdate()
    .executeTakeFirst();

  if (!item) {
    return err(new ItemNotFoundError(input.itemId));
  }

  const nextLifecycle = pipelineItemLifecycle.tryTransition(item.lifecycle, "reopen");
  if (!nextLifecycle) {
    return err(new ItemNotClosedError(input.itemId));
  }

  const now = new Date();

  const reopenedItem = await db
    .updateTable("PipelineItem")
    .set({
      lifecycle: nextLifecycle,
      updatedAt: now,
    })
    .where("id", "=", input.itemId)
    .returningAll()
    .executeTakeFirst();

  await db
    .insertInto("PipelineItemChange")
    .values({
      itemId: item.id,
      changedByUserId: ctx.actorId,
      changeType: "LIFECYCLE",
      fieldName: "LIFECYCLE",
      prevValue: item.lifecycle,
      newValue: nextLifecycle,
      createdAt: now,
      updatedAt: null,
    })
    .execute();

  return ok({
    item: reopenedItem ?? { ...item, lifecycle: nextLifecycle, updatedAt: now },
  });
}
