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

export interface DeactivateWarehouseInput {
  id: string;
}

/**
 * Function: deactivateWarehouse
 *
 * Transitions a warehouse from ACTIVE to INACTIVE status.
 * Once deactivated, the warehouse no longer accepts new stock movements,
 * but all historical records are preserved.
 */
export async function run(db: Transaction, input: DeactivateWarehouseInput, _ctx: CommandContext) {
  const { id } = input;

  // 1. Check warehouse exists
  const warehouse = await db
    .selectFrom("Warehouse")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!warehouse) {
    return err(new WarehouseNotFoundError(id));
  }

  // 2. Check status is ACTIVE
  if (warehouse.status !== "ACTIVE") {
    return err(new WarehouseNotActiveError(id));
  }

  // 3. Update status to INACTIVE
  const deactivatedWarehouse = await db
    .updateTable("Warehouse")
    .set({ status: "INACTIVE", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ warehouse: deactivatedWarehouse });
}
