import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { listingLifecycle } from "../db/listing.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelOrItemInactiveError,
  InvalidListingStatusError,
  ListingIdentifierRequiredError,
  ListingNotFoundError,
  MissingPriceLinkageError,
} from "../lib/errors.generated";
import type { ItemManagementQueries } from "../module";

export interface ActivateListingInput {
  listingId: string;
}

export async function run(
  db: Transaction,
  input: ActivateListingInput,
  ctx: CommandContext,
  itemManagementQueries: Pick<ItemManagementQueries, "getItem">,
) {
  const listing = await db
    .selectFrom("Listing")
    .selectAll()
    .where("id", "=", input.listingId)
    .forUpdate()
    .executeTakeFirst();
  if (!listing) {
    return err(new ListingNotFoundError(input.listingId));
  }
  const nextStatus = listingLifecycle.tryTransition(listing.status, "activate");
  if (!nextStatus) {
    return err(new InvalidListingStatusError(input.listingId));
  }
  if (!listing.externalIdentifier || !listing.sku) {
    return err(new ListingIdentifierRequiredError(input.listingId));
  }
  const [channel, itemResult] = await Promise.all([
    db.selectFrom("Channel").selectAll().where("id", "=", listing.channelId).executeTakeFirst(),
    itemManagementQueries.getItem(db, { id: listing.itemId }, ctx),
  ]);
  const { item } = itemResult.value;
  if (channel?.status !== "ACTIVE" || item?.status !== "ACTIVE") {
    return err(new ChannelOrItemInactiveError(input.listingId));
  }
  if (listing.requiresPriceSync && !listing.salesPriceListId) {
    return err(new MissingPriceLinkageError(input.listingId));
  }
  const updated = await db
    .updateTable("Listing")
    .set({ status: nextStatus })
    .where("id", "=", input.listingId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ listing: updated });
}
