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

export class DocumentVersion extends BaseModel {
  static tableName = 'document_versions';

  id!: string;
  documentId!: string;
  version!: number;
  hash!: string;
  minioPath!: string;
  fileSize!: string;
  mimeType!: string;
  uploadedBy!: string;
  blockchainTxHash?: string;
  createdAt!: Date;

  // Relations
  document?: Model;

  static get jsonSchema() {
    return {
      type: 'object',
      required: [
        'documentId',
        'version',
        'hash',
        'minioPath',
        'fileSize',
        'mimeType',
        'uploadedBy',
      ],
      properties: {
        id: { type: 'string', format: 'uuid' },
        documentId: { type: 'string', format: 'uuid' },
        version: { type: 'integer' },
        hash: { type: 'string', maxLength: 66 },
        minioPath: { type: 'string', maxLength: 500 },
        fileSize: { type: 'string' },
        mimeType: { type: 'string', maxLength: 100 },
        uploadedBy: { type: 'string', format: 'uuid' },
        blockchainTxHash: { type: ['string', 'null'], maxLength: 66 },
        createdAt: { type: 'string', format: 'date-time' },
      },
    };
  }

  static get relationMappings(): RelationMappingsThunk {
    return (): RelationMappings => {
      const { Document } = require('./document.model');
      return {
        document: {
          relation: Model.BelongsToOneRelation,
          modelClass: Document,
          join: {
            from: 'document_versions.document_id',
            to: 'documents.id',
          },
        },
      };
    };
  }
}
