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

export type UpdateListingInput = {
  listingId: string;
  sku?: string | null;
  externalIdentifier?: string | null;
  title?: string | null;
  requiresPriceSync?: boolean;
  salesPriceListId?: string | null;
};
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: UpdateListingInput & Partial<CF>,
  ctx: CommandContext,
) {
  void ctx;
  const {
    listingId,
    sku,
    externalIdentifier,
    title,
    requiresPriceSync,
    salesPriceListId,
    ...customFields
  } = input;
  const listing = await db
    .selectFrom("Listing")
    .selectAll()
    .where("id", "=", listingId)
    .forUpdate()
    .executeTakeFirst();
  if (!listing) {
    return err(new ListingNotFoundError(listingId));
  }
  if (listing.status === "RETIRED") {
    return err(new ListingNotEditableError(listingId));
  }
  if (externalIdentifier && externalIdentifier !== listing.externalIdentifier) {
    const siblings = await db
      .selectFrom("Listing")
      .selectAll()
      .where("channelId", "=", listing.channelId)
      .execute();
    if (
      siblings.some(
        (item) => item.id !== listing.id && item.externalIdentifier === externalIdentifier,
      )
    ) {
      return err(new DuplicateExternalIdentifierError(externalIdentifier));
    }
  }
  const updates: Updateable<"Listing"> = { ...(customFields as Updateable<"Listing">) };
  if (sku !== undefined) updates.sku = sku;
  if (externalIdentifier !== undefined) updates.externalIdentifier = externalIdentifier;
  if (title !== undefined) updates.title = title;
  if (requiresPriceSync !== undefined) updates.requiresPriceSync = requiresPriceSync;
  if (salesPriceListId !== undefined) updates.salesPriceListId = salesPriceListId;

  if (Object.keys(updates).length === 0) {
    return ok({ listing });
  }

  const updated = await db
    .updateTable("Listing")
    .set(updates)
    .where("id", "=", listingId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ listing: updated });
}
