import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { HydratedDocument, Types } from 'mongoose'

export type WebhookSubscriptionDocument = HydratedDocument<WebhookSubscription>

// Booking lifecycle events a tenant can subscribe to. Kept in sync with the
// event names WebhookService.dispatch emits from BookingsService.
export type WebhookEvent = 'booking.created' | 'booking.cancelled' | 'booking.rescheduled'

export const WEBHOOK_EVENTS: WebhookEvent[] = ['booking.created', 'booking.cancelled', 'booking.rescheduled']

// A tenant-configured HTTPS endpoint that receives signed POSTs for booking
// lifecycle events. The `secret` is the HMAC-SHA256 key used to sign each
// delivery body (header X-Dezky-Signature); the tenant stores the same secret to
// verify. Inactive subscriptions are skipped by the dispatcher.
@Schema({ collection: 'scheduling_webhook_subscriptions', timestamps: true })
export class WebhookSubscription {
  @Prop({ type: Types.ObjectId, ref: 'Tenant', required: true, index: true })
  tenantId!: Types.ObjectId

  @Prop({ required: true, trim: true })
  url!: string

  // HMAC signing secret. Generated server-side; surfaced to the admin once on
  // create/rotate so they can configure their receiver's verification.
  @Prop({ required: true })
  secret!: string

  @Prop({ type: [String], enum: WEBHOOK_EVENTS, default: WEBHOOK_EVENTS })
  events!: WebhookEvent[]

  @Prop({ default: true })
  active!: boolean
}

export const WebhookSubscriptionSchema = SchemaFactory.createForClass(WebhookSubscription)
