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

export class Approval extends BaseModel {
  static tableName = 'approvals';

  id!: string;
  requestId!: string;
  departmentId!: string;
  status!: ApprovalStatus;
  remarks?: string;
  remarksHash?: string;
  reviewedDocuments?: string[];
  blockchainTxHash?: string;
  isActive!: boolean;
  invalidatedAt?: Date;
  invalidationReason?: string;
  revalidatedAt?: Date;
  approvedBy?: string;
  rejectionReason?: string;
  requiredDocuments?: string[];
  completedAt?: Date;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  request?: Model;
  department?: Model;

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['requestId', 'departmentId'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        requestId: { type: 'string', format: 'uuid' },
        departmentId: { type: 'string', format: 'uuid' },
        status: { type: 'string', maxLength: 50, default: 'PENDING' },
        remarks: { type: ['string', 'null'] },
        remarksHash: { type: ['string', 'null'], maxLength: 66 },
        reviewedDocuments: { type: ['array', 'null'], items: { type: 'string' } },
        blockchainTxHash: { type: ['string', 'null'], maxLength: 66 },
        isActive: { type: 'boolean', default: true },
        invalidatedAt: { type: ['string', 'null'], format: 'date-time' },
        invalidationReason: { type: ['string', 'null'], maxLength: 255 },
        revalidatedAt: { type: ['string', 'null'], format: 'date-time' },
        approvedBy: { type: ['string', 'null'] },
        rejectionReason: { type: ['string', 'null'] },
        requiredDocuments: { type: ['array', 'null'], items: { type: 'string' } },
        completedAt: { 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 { Department } = require('./department.model');
      return {
        request: {
          relation: Model.BelongsToOneRelation,
          modelClass: LicenseRequest,
          join: {
            from: 'approvals.request_id',
            to: 'license_requests.id',
          },
        },
        department: {
          relation: Model.BelongsToOneRelation,
          modelClass: Department,
          join: {
            from: 'approvals.department_id',
            to: 'departments.id',
          },
        },
      };
    };
  }
}
