import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { PartnerRoleRole } from "../generated/enums";
import type { Transaction } from "../generated/kysely-tailordb";
import { PartnerNotFoundError, PartnerNotActiveError } from "../lib/errors.generated";

export interface RemoveRoleFromPartnerInput {
  partnerId: string;
  role: PartnerRoleRole;
}

/**
 * Function: removeRoleFromPartner
 *
 * Removes a CUSTOMER or SUPPLIER role from an ACTIVE partner. Idempotent —
 * returns success even if the role was not assigned.
 */
export async function run(
  db: Transaction,
  input: RemoveRoleFromPartnerInput,
  _ctx: CommandContext,
) {
  const { partnerId, role } = input;

  // 1. Check partner exists and is ACTIVE
  const partner = await db
    .selectFrom("BusinessPartner")
    .selectAll()
    .where("id", "=", partnerId)
    .forUpdate()
    .executeTakeFirst();

  if (!partner) {
    return err(new PartnerNotFoundError(partnerId));
  }

  if (partner.status !== "ACTIVE") {
    return err(new PartnerNotActiveError(partnerId));
  }

  // 2. Check if role exists
  const existingRole = await db
    .selectFrom("PartnerRole")
    .selectAll()
    .where("partnerId", "=", partnerId)
    .where("role", "=", role)
    .executeTakeFirst();

  // 3. Idempotent — return success even if not found
  if (!existingRole) {
    return ok({ deleted: true });
  }

  // 4. Delete the role
  await db
    .deleteFrom("PartnerRole")
    .where("partnerId", "=", partnerId)
    .where("role", "=", role)
    .execute();

  return ok({ deleted: true });
}
