import { Column, Entity, Index } from "typeorm";
import { BaseEntity } from "@edr/api-common";
import { ProviderMethod } from "@edr/types";

/**
 * Idempotency + audit record for every inbound provider webhook. The unique
 * (provider, external_event_id) pair is the dedupe key: a duplicate insert hits the unique
 * violation and the handler short-circuits with a 200 ack.
 */
@Entity({ name: "payment_webhook_event" })
@Index("uq_payment_webhook_event_external", ["provider", "externalEventId"], {
  unique: true,
})
export class PaymentWebhookEvent extends BaseEntity {
  @Column({ name: "provider", type: "varchar", length: 16 })
  provider!: ProviderMethod;

  /** Provider event id when given (e.g. Waafi X-Webhook-Event-Id), else derived from the payload. */
  @Column({ name: "external_event_id", type: "varchar", length: 191 })
  externalEventId!: string;

  @Column({
    name: "merchant_order_id",
    type: "varchar",
    length: 64,
    nullable: true,
  })
  merchantOrderId?: string | null;

  @Column({
    name: "provider_txn_id",
    type: "varchar",
    length: 128,
    nullable: true,
  })
  providerTxnId?: string | null;

  @Column({ name: "signature_valid", type: "boolean", default: false })
  signatureValid!: boolean;

  /** Raw provider status string as sent (pre-mapping). */
  @Column({ name: "status", type: "varchar", length: 64, nullable: true })
  status?: string | null;

  /** Full webhook body — hostile input, stored verbatim for audit/replay analysis. */
  @Column({ name: "payload", type: "jsonb" })
  payload!: Record<string, unknown>;

  @Column({ name: "received_at", type: "timestamptz", default: () => "now()" })
  receivedAt!: Date;

  @Column({ name: "processed_at", type: "timestamptz", nullable: true })
  processedAt?: Date | null;

  @Column({ name: "processing_error", type: "text", nullable: true })
  processingError?: string | null;
}
