import { Model, RelationMappings, RelationMappingsThunk } from 'objection';
import { BaseModel } from './base.model';

export class Webhook extends BaseModel {
  static tableName = 'webhooks';

  id!: string;
  departmentId!: string;
  url!: string;
  events!: string[];
  secretHash!: string;
  isActive!: boolean;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  department?: Model;
  logs?: Model[];

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['departmentId', 'url', 'events', 'secretHash'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        departmentId: { type: 'string', format: 'uuid' },
        url: { type: 'string', maxLength: 500 },
        events: { type: 'array', items: { type: 'string' } },
        secretHash: { type: 'string', maxLength: 255 },
        isActive: { type: 'boolean', default: true },
        createdAt: { type: 'string', format: 'date-time' },
        updatedAt: { type: 'string', format: 'date-time' },
      },
    };
  }

  static get relationMappings(): RelationMappingsThunk {
    return (): RelationMappings => {
      const { Department } = require('./department.model');
      const { WebhookLog } = require('./webhook-log.model');
      return {
        department: {
          relation: Model.BelongsToOneRelation,
          modelClass: Department,
          join: {
            from: 'webhooks.department_id',
            to: 'departments.id',
          },
        },
        logs: {
          relation: Model.HasManyRelation,
          modelClass: WebhookLog,
          join: {
            from: 'webhooks.id',
            to: 'webhook_logs.webhook_id',
          },
        },
      };
    };
  }
}
