import type { DB } from "../generated/kysely-tailordb";
import { IdentifierRequiredError } from "../lib/errors.generated";
import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetListingByExternalIdentifierInput {
  channelId: string;
  externalIdentifier: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetListingByExternalIdentifierInput) {
  if (!input.channelId || !input.externalIdentifier) {
    return err(
      new IdentifierRequiredError(input.channelId || input.externalIdentifier || "listing"),
    );
  }
  const listing = await db
    .selectFrom("Listing")
    .selectAll()
    .where("channelId", "=", input.channelId)
    .where("externalIdentifier", "=", input.externalIdentifier)
    .executeTakeFirst();
  return ok({ listing: listing ?? null });
}
