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

export interface PauseListingInput {
  listingId: string;
}

export async function run(db: Transaction, input: PauseListingInput, 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 !== "ACTIVE") {
    return err(new InvalidListingStatusError(input.listingId));
  }
  const updated = await db
    .updateTable("Listing")
    .set({ status: "PAUSED", updatedAt: new Date() })
    .where("id", "=", input.listingId)
    .returningAll()
    .executeTakeFirst();
  return ok({ listing: updated! });
}
