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

export class Document extends BaseModel {
  static tableName = 'documents';

  id!: string;
  requestId!: string;
  docType!: string;
  originalFilename!: string;
  currentVersion!: number;
  currentHash!: string;
  minioBucket!: string;
  isActive!: boolean;
  downloadCount!: number;
  lastDownloadedAt?: string;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  request?: Model;
  versions?: Model[];

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['requestId', 'docType', 'originalFilename', 'currentHash', 'minioBucket'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        requestId: { type: 'string', format: 'uuid' },
        docType: { type: 'string', maxLength: 100 },
        originalFilename: { type: 'string', maxLength: 255 },
        currentVersion: { type: 'integer', default: 1 },
        currentHash: { type: 'string', maxLength: 66 },
        minioBucket: { type: 'string', maxLength: 100 },
        isActive: { type: 'boolean', default: true },
        downloadCount: { type: 'integer', default: 0 },
        lastDownloadedAt: { 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');
      const { DocumentVersion } = require('./document-version.model');
      return {
        request: {
          relation: Model.BelongsToOneRelation,
          modelClass: LicenseRequest,
          join: {
            from: 'documents.request_id',
            to: 'license_requests.id',
          },
        },
        versions: {
          relation: Model.HasManyRelation,
          modelClass: DocumentVersion,
          join: {
            from: 'documents.id',
            to: 'document_versions.document_id',
          },
        },
      };
    };
  }
}
