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

export interface ActivateListingInput {
  listingId: string;
}

export async function run(db: Transaction, input: ActivateListingInput, 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 (!["DRAFT", "PAUSED"].includes(listing.status)) {
    return err(new InvalidListingStatusError(input.listingId));
  }
  if (!listing.externalIdentifier || !listing.sku) {
    return err(new ListingIdentifierRequiredError(input.listingId));
  }
  const [channel, item] = await Promise.all([
    db.selectFrom("Channel").selectAll().where("id", "=", listing.channelId).executeTakeFirst(),
    db.selectFrom("Item").selectAll().where("id", "=", listing.itemId).executeTakeFirst(),
  ]);
  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: "ACTIVE", updatedAt: new Date() })
    .where("id", "=", input.listingId)
    .returningAll()
    .executeTakeFirst();
  return ok({ listing: updated! });
}
