import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { InventorySupplyPlanSourceType } from "../generated/enums";
import type { DB } from "../generated/kysely-tailordb";
import { getOpenInventorySupplyPlanQuantity } from "../internal/inventorySupplyPlan";

export interface GetInventorySupplyPlanByIdInput {
  id: string;
}

export interface GetInventorySupplyPlanBySourceLineInput {
  sourceType: InventorySupplyPlanSourceType;
  sourceLineId: string;
}

export type GetInventorySupplyPlanInput =
  | GetInventorySupplyPlanByIdInput
  | GetInventorySupplyPlanBySourceLineInput;

export async function run(db: ReadonlyDB<DB>, input: GetInventorySupplyPlanInput) {
  let query = db.selectFrom("InventorySupplyPlan").selectAll();

  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query
      .where("sourceType", "=", input.sourceType)
      .where("sourceLineId", "=", input.sourceLineId);
  }

  const supplyPlan = await query.executeTakeFirst();
  if (!supplyPlan) {
    return ok({ supplyPlan: null });
  }

  return ok({
    supplyPlan: {
      ...supplyPlan,
      openQuantity:
        supplyPlan.status === "OPEN"
          ? getOpenInventorySupplyPlanQuantity(supplyPlan).toString()
          : "0",
    },
  });
}
