import { Model, QueryContext } from 'objection';
import { v4 as uuidv4 } from 'uuid';
import { TransactionType, TransactionStatus } from '../../common/enums';
import { BaseModel } from './base.model';

export class BlockchainTransaction extends BaseModel {
  static tableName = 'blockchain_transactions';

  id!: string;
  txHash!: string;
  txType!: TransactionType;
  relatedEntityType!: string;
  relatedEntityId!: string;
  fromAddress!: string;
  toAddress?: string;
  status!: TransactionStatus;
  blockNumber?: string;
  gasUsed?: string;
  errorMessage?: string;
  createdAt!: Date;
  confirmedAt?: Date;

  async $beforeInsert(queryContext: QueryContext): Promise<void> {
    await super.$beforeInsert(queryContext);
    if (!this.id) {
      this.id = uuidv4();
    }
    this.createdAt = new Date();
  }

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['txHash', 'txType', 'relatedEntityType', 'relatedEntityId', 'fromAddress'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        txHash: { type: 'string', maxLength: 66 },
        txType: { type: 'string', maxLength: 50 },
        relatedEntityType: { type: 'string', maxLength: 50 },
        relatedEntityId: { type: 'string', format: 'uuid' },
        fromAddress: { type: 'string', maxLength: 42 },
        toAddress: { type: ['string', 'null'], maxLength: 42 },
        status: { type: 'string', maxLength: 20, default: 'PENDING' },
        blockNumber: { type: ['string', 'null'] },
        gasUsed: { type: ['string', 'null'] },
        errorMessage: { type: ['string', 'null'] },
        createdAt: { type: 'string', format: 'date-time' },
        confirmedAt: { type: ['string', 'null'], format: 'date-time' },
      },
    };
  }
}
