import { createHash } from 'crypto';

export type IdempotencyInput = {
  tenantId: string;
  entityId: string;
  operation: string;
  resourceId?: string;
  payload?: Record<string, unknown>;
};

export function deriveIdempotencyKey(input: IdempotencyInput): string {
  const canonical = JSON.stringify({
    tenantId: input.tenantId,
    entityId: input.entityId,
    operation: input.operation,
    resourceId: input.resourceId ?? '',
    payload: input.payload ?? {},
  });
  return createHash('sha256').update(canonical).digest('hex');
}

export class IdempotencyStore {
  private readonly keys = new Set<string>();

  has(key: string): boolean {
    return this.keys.has(key);
  }

  record(key: string): boolean {
    if (this.keys.has(key)) return false;
    this.keys.add(key);
    return true;
  }
}
