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

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 updated = await db
    .updateTable("Listing")
    .set({
      sku: input.sku ?? listing.sku,
      externalIdentifier: input.externalIdentifier ?? listing.externalIdentifier,
      title: input.title ?? listing.title,
      requiresPriceSync: input.requiresPriceSync ?? listing.requiresPriceSync,
      salesPriceListId: input.salesPriceListId ?? listing.salesPriceListId,
      updatedAt: new Date(),
    })
    .where("id", "=", input.listingId)
    .returningAll()
    .executeTakeFirst();
  return ok({ listing: updated! });
}
