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 RetireListingInput {
  listingId: string;
}

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