import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { License } from './license.entity';

@Entity('webhooks')
@Index(['license_id'])
export class Webhook {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid' })
  license_id: string;

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

  @Column({ type: 'text' })
  url: string;

  /**
   * Comma-separated event keys stored as plain text in Postgres.
   * TypeORM simple-array serialises string[] ↔ 'event1,event2' automatically.
   */
  @Column({ type: 'simple-array' })
  events: string[];

  /** HMAC-SHA256 signing secret. Auto-generated on create if omitted. */
  @Column({ type: 'varchar', length: 128 })
  secret: string;

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

  /** Timestamp of the most recent delivery attempt (success or failure). */
  @Column({ type: 'timestamptz', nullable: true })
  last_delivery_at: Date | null;

  /** 'ok' | 'failed' — outcome of the most recent delivery attempt. */
  @Column({ type: 'varchar', length: 20, nullable: true })
  last_status: string | null;

  @Column({ type: 'timestamptz', default: () => 'NOW()' })
  created_at: Date;

  @ManyToOne(() => License, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'license_id' })
  license: License;
}
