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(db: Transaction, input: UpdateListingInput, ctx: CommandContext) {
  void ctx;
  const listing = await db
    .selectFrom("Listing")
    .selectAll()
    .where("id", "=", input.listingId)
    .forUpdate()
    .executeTakeFirst();
  if (!listing) {
    return err(new ListingNotFoundError(input.listingId));
  }
  if (listing.status === "RETIRED") {
    return err(new ListingNotEditableError(input.listingId));
  }
  if (input.externalIdentifier && input.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 === input.externalIdentifier,
      )
    ) {
      return err(new DuplicateExternalIdentifierError(input.externalIdentifier));
    }
  }
  const updates: Updateable<"Listing"> = {};
  if (input.sku !== undefined) updates.sku = input.sku;
  if (input.externalIdentifier !== undefined) updates.externalIdentifier = input.externalIdentifier;
  if (input.title !== undefined) updates.title = input.title;
  if (input.requiresPriceSync !== undefined) updates.requiresPriceSync = input.requiresPriceSync;
  if (input.salesPriceListId !== undefined) updates.salesPriceListId = input.salesPriceListId;

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

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