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 AssignRoleToPartnerInput {
  partnerId: string;
  role: PartnerRoleRole;
}

/**
 * Function: assignRoleToPartner
 *
 * Assigns a CUSTOMER or SUPPLIER role to an ACTIVE partner. Idempotent —
 * returns the existing role if already assigned.
 */
export async function run(db: Transaction, input: AssignRoleToPartnerInput, _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 already assigned (idempotent)
  const existingRole = await db
    .selectFrom("PartnerRole")
    .selectAll()
    .where("partnerId", "=", partnerId)
    .where("role", "=", role)
    .executeTakeFirst();

  if (existingRole) {
    return ok({ partnerRole: existingRole });
  }

  // 3. Create new role
  const partnerRole = await db
    .insertInto("PartnerRole")
    .values({
      partnerId,
      role,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ partnerRole });
}
