import type { Transaction } from "../generated/kysely-tailordb";
import {
  PartnerNotFoundError,
  PartnerNotActiveError,
  InvalidRoleError,
} 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 AssignRoleToPartnerInput {
  partnerId: string;
  role: string;
}

/**
 * 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. 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 already assigned (idempotent)
  const existingRole = await db
    .selectFrom("PartnerRole")
    .selectAll()
    .where("partnerId", "=", partnerId)
    .where("role", "=", validRole)
    .executeTakeFirst();

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

  // 4. Create new role
  const partnerRole = await db
    .insertInto("PartnerRole")
    .values({
      partnerId,
      role: validRole,
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ partnerRole: partnerRole! });
}
