import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  DuplicateListingIdentityError,
  ItemNotActiveError,
  ItemNotFoundError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CreateListingInput {
  channelId: string;
  itemId: string;
  sku?: string;
  externalIdentifier?: string | null;
  title?: string;
  requiresPriceSync?: boolean;
  salesPriceListId?: string | null;
}

export async function run(db: Transaction, input: CreateListingInput, ctx: CommandContext) {
  void ctx;
  const channel = await db
    .selectFrom("Channel")
    .selectAll()
    .where("id", "=", input.channelId)
    .executeTakeFirst();
  if (!channel) {
    return err(new ChannelNotFoundError(input.channelId));
  }
  const item = await db
    .selectFrom("Item")
    .selectAll()
    .where("id", "=", input.itemId)
    .executeTakeFirst();
  if (!item) {
    return err(new ItemNotFoundError(input.itemId));
  }
  if (item.status !== "ACTIVE") {
    return err(new ItemNotActiveError(input.itemId));
  }
  const existing = await db
    .selectFrom("Listing")
    .selectAll()
    .where("channelId", "=", input.channelId)
    .execute();
  if (
    existing.some(
      (listing) =>
        (input.externalIdentifier != null &&
          listing.externalIdentifier === input.externalIdentifier) ||
        (input.sku != null && listing.sku === input.sku),
    )
  ) {
    return err(
      new DuplicateListingIdentityError(input.externalIdentifier ?? input.sku ?? "listing"),
    );
  }
  const listing = await db
    .insertInto("Listing")
    .values({
      companyId: channel.companyId,
      channelId: input.channelId,
      itemId: input.itemId,
      sku: input.sku ?? null,
      externalIdentifier: input.externalIdentifier ?? null,
      title: input.title ?? null,
      status: "DRAFT",
      requiresPriceSync: input.requiresPriceSync ?? false,
      salesPriceListId: input.salesPriceListId ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();
  return ok({ listing: listing! });
}
