import type { DB } from "../generated/kysely-tailordb";
import { SerialNumberNotFoundError } from "../lib/errors.generated";
import { ok, err, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetSerialNumberHistoryInput {
  serialNumberId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetSerialNumberHistoryInput) {
  const serialNumber = await db
    .selectFrom("SerialNumber")
    .selectAll()
    .where("id", "=", input.serialNumberId)
    .executeTakeFirst();

  if (!serialNumber) {
    return err(new SerialNumberNotFoundError(input.serialNumberId));
  }

  const moveLines = await db
    .selectFrom("StockMoveLine")
    .innerJoin("StockMovement", "StockMovement.id", "StockMoveLine.stockMovementId")
    .selectAll("StockMoveLine")
    .select(["StockMovement.movementType", "StockMovement.executedAt", "StockMovement.status"])
    .where("StockMoveLine.serialNumberId", "=", input.serialNumberId)
    .orderBy("StockMoveLine.createdAt", "asc")
    .execute();

  return ok({ moveLines });
}
