/**
 * WebhookEvent Entity
 * Individual webhook events with dispatch tracking
 * Compatible with erp-core event.entity
 *
 * @module Webhooks
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
} from 'typeorm';

export type WebhookEventStatus = 'pending' | 'processing' | 'dispatched' | 'failed';

@Entity({ name: 'events', schema: 'webhooks' })
export class WebhookEvent {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'event_type', type: 'varchar', length: 100 })
  eventType: string;

  @Column({ name: 'payload', type: 'jsonb' })
  payload: Record<string, any>;

  @Column({ name: 'resource_type', type: 'varchar', length: 100, nullable: true })
  resourceType: string;

  @Column({ name: 'resource_id', type: 'uuid', nullable: true })
  resourceId: string;

  @Column({ name: 'triggered_by', type: 'uuid', nullable: true })
  triggeredBy: string;

  @Index()
  @Column({ name: 'status', type: 'varchar', length: 20, default: 'pending' })
  status: WebhookEventStatus;

  @Column({ name: 'processed_at', type: 'timestamptz', nullable: true })
  processedAt: Date;

  @Column({ name: 'dispatched_endpoints', type: 'int', default: 0 })
  dispatchedEndpoints: number;

  @Column({ name: 'failed_endpoints', type: 'int', default: 0 })
  failedEndpoints: number;

  @Index()
  @Column({ name: 'idempotency_key', type: 'varchar', length: 255, nullable: true })
  idempotencyKey: string;

  @Column({ name: 'metadata', type: 'jsonb', default: {} })
  metadata: Record<string, any>;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

  @Column({ name: 'expires_at', type: 'timestamptz', nullable: true })
  expiresAt: Date;
}
