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

type ValidRole = "CUSTOMER" | "SUPPLIER";
const VALID_ROLES: readonly ValidRole[] = ["CUSTOMER", "SUPPLIER"] as const;

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

/**
 * 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. Validate role
  if (!VALID_ROLES.includes(role as ValidRole)) {
    return err(new InvalidRoleError(role ?? ""));
  }
  const validRole = role as ValidRole;

  // 2. 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));
  }

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

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

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

  return ok({ deleted: true });
}
