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

export class Department extends BaseModel {
  static tableName = 'departments';

  id!: string;
  code!: string;
  name!: string;
  walletAddress?: string;
  apiKeyHash?: string;
  apiSecretHash?: string;
  webhookUrl?: string;
  webhookSecretHash?: string;
  isActive!: boolean;
  description?: string;
  contactEmail?: string;
  contactPhone?: string;
  lastWebhookAt?: Date;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  approvals?: Model[];
  webhooks?: Model[];

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['code', 'name'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        code: { type: 'string', maxLength: 50 },
        name: { type: 'string', maxLength: 255 },
        walletAddress: { type: ['string', 'null'], maxLength: 42 },
        apiKeyHash: { type: ['string', 'null'], maxLength: 255 },
        apiSecretHash: { type: ['string', 'null'], maxLength: 255 },
        webhookUrl: { type: ['string', 'null'], maxLength: 500 },
        webhookSecretHash: { type: ['string', 'null'], maxLength: 255 },
        isActive: { type: 'boolean', default: true },
        description: { type: ['string', 'null'] },
        contactEmail: { type: ['string', 'null'] },
        contactPhone: { type: ['string', 'null'] },
        lastWebhookAt: { type: ['string', 'null'], format: 'date-time' },
        createdAt: { type: 'string', format: 'date-time' },
        updatedAt: { type: 'string', format: 'date-time' },
      },
    };
  }

  static get relationMappings(): RelationMappingsThunk {
    return (): RelationMappings => {
      const { Approval } = require('./approval.model');
      const { Webhook } = require('./webhook.model');
      return {
        approvals: {
          relation: Model.HasManyRelation,
          modelClass: Approval,
          join: {
            from: 'departments.id',
            to: 'approvals.department_id',
          },
        },
        webhooks: {
          relation: Model.HasManyRelation,
          modelClass: Webhook,
          join: {
            from: 'departments.id',
            to: 'webhooks.department_id',
          },
        },
      };
    };
  }
}
