import { Model, RelationMappings, RelationMappingsThunk } from 'objection';
import { BaseModel } from './base.model';
import { WorkflowStage } from '../../common/interfaces/request-context.interface';

export class Workflow extends BaseModel {
  static tableName = 'workflows';

  id!: string;
  workflowType!: string;
  name!: string;
  description?: string;
  version!: number;
  definition!: any;
  isActive!: boolean;
  createdBy?: string;
  updatedBy?: string;
  deactivatedAt?: Date;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  requests?: Model[];

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['workflowType', 'name', 'definition'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        workflowType: { type: 'string', maxLength: 100 },
        name: { type: 'string', maxLength: 255 },
        description: { type: ['string', 'null'] },
        version: { type: 'integer', default: 1 },
        definition: { type: 'object' },
        isActive: { type: 'boolean', default: true },
        createdBy: { type: ['string', 'null'], format: 'uuid' },
        updatedBy: { type: ['string', 'null'], format: 'uuid' },
        deactivatedAt: { 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 { LicenseRequest } = require('./license-request.model');
      return {
        requests: {
          relation: Model.HasManyRelation,
          modelClass: LicenseRequest,
          join: {
            from: 'workflows.id',
            to: 'license_requests.workflow_id',
          },
        },
      };
    };
  }
}
