/**
 * Autotask Webhook Types
 * Based on: https://autotask.net/help/DeveloperHelp/Content/APIs/Webhooks/WEBHOOKS.htm
 */

/**
 * Webhook event types from Autotask
 */
export enum WebhookEventType {
  CREATE = 'create',
  UPDATE = 'update',
  DELETE = 'delete',
}

/**
 * Supported entity types for webhooks
 */
export enum WebhookEntityType {
  COMPANIES = 'Companies',
  TICKETS = 'Tickets',
  TICKET_NOTES = 'TicketNotes',
  TASKS = 'Tasks',
  PROJECTS = 'Projects',
  TIME_ENTRIES = 'TimeEntries',
  CONTACTS = 'Contacts',
  CONTRACTS = 'Contracts',
  CONFIGURATION_ITEMS = 'ConfigurationItems',
}

/**
 * Entities Autotask actually exposes a webhook REST endpoint for.
 * TimeEntries, Tasks, Projects, Contracts return 404 — not supported by Autotask.
 */
export const WEBHOOK_SUPPORTED_ENTITIES: WebhookEntityType[] = [
  WebhookEntityType.COMPANIES,
  WebhookEntityType.CONTACTS,
  WebhookEntityType.CONFIGURATION_ITEMS,
  WebhookEntityType.TICKETS,
  WebhookEntityType.TICKET_NOTES,
];

/**
 * Autotask webhook registration request
 */
export interface AutotaskWebhookRegistration {
  IsActive: boolean;
  DeactivationUrl: string;
  IsSubscribedToCreateEvents?: boolean;
  IsSubscribedToUpdateEvents?: boolean;
  IsSubscribedToDeleteEvents?: boolean;
  Name: string;
  SecretKey: string;
  SendThresholdExceededNotification: boolean;
  WebhookUrl: string;
  NotificationEmailAddress: string;
}

/**
 * Autotask webhook field trigger
 */
export interface AutotaskWebhookFieldTrigger {
  FieldID: number;
  IsDisplayAlwaysField: boolean;
  IsSubscribedField: boolean;
  WebhookID: number;
}

/**
 * Autotask webhook registration result
 */
export interface AutotaskWebhookRegistrationResult {
  entityType: WebhookEntityType;
  webhookId: number;
  fieldsRegistered: number;
  excludedResources: number;
  success: boolean;
  error?: string;
}

/**
 * Raw Autotask webhook payload as actually sent by Autotask
 */
export interface AutotaskRawWebhookPayload {
  Action: string;           // "Create", "Update", "Delete"
  Guid: string;             // Unique event GUID
  EntityType: string;       // Singular: "Ticket", "Company", "Contact", "ConfigurationItem", "TicketNote"
  Id: number;               // Entity ID
  Fields?: Record<string, string>;  // Changed/created fields
  EventTime: string;        // ISO timestamp
  SequenceNumber?: number;
  PersonId?: number;        // Resource who triggered the event
}

/**
 * Normalized webhook payload used internally
 */
export interface AutotaskWebhookPayload {
  eventId: string;
  eventType: WebhookEventType;
  entityType: WebhookEntityType;
  entityId: number;
  eventTimestamp: string;
  fields?: Record<string, string>;
  entity?: Record<string, any>;
  personId?: number;
}

/**
 * Map Autotask singular EntityType to our WebhookEntityType enum
 */
const ENTITY_TYPE_MAP: Record<string, WebhookEntityType> = {
  'Company': WebhookEntityType.COMPANIES,
  'Account': WebhookEntityType.COMPANIES,           // Autotask legacy name
  'Contact': WebhookEntityType.CONTACTS,
  'ConfigurationItem': WebhookEntityType.CONFIGURATION_ITEMS,
  'InstalledProduct': WebhookEntityType.CONFIGURATION_ITEMS, // Autotask actual payload name
  'Ticket': WebhookEntityType.TICKETS,
  'TicketNote': WebhookEntityType.TICKET_NOTES,
  'TimeEntry': WebhookEntityType.TIME_ENTRIES,
  'Task': WebhookEntityType.TASKS,
  'Project': WebhookEntityType.PROJECTS,
  'Contract': WebhookEntityType.CONTRACTS,
};

/**
 * Map Autotask Action string to our WebhookEventType enum
 */
const ACTION_MAP: Record<string, WebhookEventType> = {
  'Create': WebhookEventType.CREATE,
  'Update': WebhookEventType.UPDATE,
  'Delete': WebhookEventType.DELETE,
};

/**
 * Normalize a raw Autotask webhook payload into our internal format
 */
export function normalizeWebhookPayload(raw: AutotaskRawWebhookPayload): AutotaskWebhookPayload {
  const entityType = ENTITY_TYPE_MAP[raw.EntityType];
  if (!entityType) {
    throw new Error(`Unknown Autotask EntityType: ${raw.EntityType}`);
  }

  const eventType = ACTION_MAP[raw.Action];
  if (!eventType) {
    throw new Error(`Unknown Autotask Action: ${raw.Action}`);
  }

  return {
    eventId: raw.Guid,
    eventType,
    entityType,
    entityId: raw.Id,
    eventTimestamp: raw.EventTime,
    fields: raw.Fields,
    personId: raw.PersonId,
  };
}

/**
 * Webhook processing result
 */
export interface WebhookProcessingResult {
  success: boolean;
  eventId: string;
  entityType: WebhookEntityType;
  entityId: number;
  action: 'created' | 'updated' | 'deleted' | 'skipped';
  error?: string;
  processingTime: number;
}

/**
 * Webhook log entry for tracking
 */
export interface WebhookLog {
  id?: number;
  event_id: string;
  entity_type: string;
  entity_id: number;
  event_type: WebhookEventType;
  status: 'pending' | 'processed' | 'failed';
  error_message?: string;
  source_ip?: string;
  user_agent?: string;
  received_at: Date;
  processed_at?: Date;
  processing_time_ms?: number;
  payload: Record<string, any>;
}

/**
 * Webhook configuration
 */
export interface WebhookConfig {
  id?: number;
  entity_type: WebhookEntityType;
  event_types: WebhookEventType[];
  is_active: boolean;
  autotask_webhook_id?: string;
  created_at?: Date;
  updated_at?: Date;
}
