/**
 * Movement Dashboard supplier guard (client 2026-11-23).
 *
 * Picking / changing / removing a supplier on an MD row needs the role's
 * Supplier right (Edit+) on top of Transport / Activity Assignment. A
 * save that only re-sends the SAME suppliers (e.g. a cost or vehicle-type
 * edit on an extra-supplier row) is not a change and stays allowed.
 */

export interface SupplierRef {
  supplier_id?: string | null;
  supplier_name_text?: string | null;
}

/** A supplier's identity — master id, else the typed name (case-insensitive). */
export function supplierKey(s: SupplierRef | null | undefined): string | null {
  if (!s) return null;
  if (s.supplier_id) return `id:${s.supplier_id}`;
  const name = (s.supplier_name_text || '').trim().toLowerCase();
  return name ? `name:${name}` : null;
}

/** True when the two supplier lists differ (order ignored). */
export function supplierListChanged(current: SupplierRef[], next: SupplierRef[]): boolean {
  const keys = (list: SupplierRef[]) =>
    list
      .map(supplierKey)
      .filter((k): k is string => k !== null)
      .sort();
  const a = keys(current);
  const b = keys(next);
  return a.length !== b.length || a.some((k, i) => k !== b[i]);
}

/** True when a single-supplier patch changes the row's main supplier. */
export function primarySupplierChanged(item: SupplierRef, dto: SupplierRef): boolean {
  const next: SupplierRef = {
    supplier_id: dto.supplier_id !== undefined ? dto.supplier_id : item.supplier_id,
    supplier_name_text:
      dto.supplier_id !== undefined && dto.supplier_id
        ? null
        : dto.supplier_name_text !== undefined
          ? dto.supplier_name_text
          : item.supplier_name_text,
  };
  return supplierKey(item) !== supplierKey(next);
}

/** Bulk patches set a supplier on many rows — any supplier field counts. */
export function bulkTouchesSupplier(dto: SupplierRef & { supplier_phone_text?: string | null }) {
  return (
    !!dto.supplier_id ||
    !!(dto.supplier_name_text || '').trim() ||
    (dto.supplier_id === null && dto.supplier_name_text === null)
  );
}

export const SUPPLIER_EDIT_REQUIRED =
  'Changing the supplier needs Supplier edit rights for your role (Settings → Roles → Suppliers).';
