/**
 * WebhookSubscription Entity
 * Links endpoints to specific event types
 * Compatible with erp-core subscription.entity
 *
 * @module Webhooks
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  Unique,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { WebhookEndpoint } from './endpoint.entity';
import { WebhookEventType } from './event-type.entity';

@Entity({ name: 'subscriptions', schema: 'webhooks' })
@Unique(['endpointId', 'eventTypeId'])
export class WebhookSubscription {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'endpoint_id', type: 'uuid' })
  endpointId: string;

  @Index()
  @Column({ name: 'event_type_id', type: 'uuid' })
  eventTypeId: string;

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

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

  @Column({ name: 'payload_template', type: 'jsonb', nullable: true })
  payloadTemplate: Record<string, any>;

  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive: boolean;

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt: Date;

  @ManyToOne(() => WebhookEndpoint, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'endpoint_id' })
  endpoint: WebhookEndpoint;

  @ManyToOne(() => WebhookEventType, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'event_type_id' })
  eventType: WebhookEventType;
}
