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

export class AuditLog extends BaseModel {
  static tableName = 'audit_logs';

  id!: string;
  entityType!: string;
  entityId!: string;
  action!: string;
  actorType!: string;
  actorId?: string;
  oldValue?: Record<string, unknown>;
  newValue?: Record<string, unknown>;
  ipAddress?: string;
  userAgent?: string;
  correlationId?: string;
  createdAt!: 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: ['entityType', 'entityId', 'action', 'actorType'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        entityType: { type: 'string', maxLength: 50 },
        entityId: { type: 'string', format: 'uuid' },
        action: { type: 'string', maxLength: 50 },
        actorType: { type: 'string', maxLength: 50 },
        actorId: { type: ['string', 'null'], format: 'uuid' },
        oldValue: { type: ['object', 'null'] },
        newValue: { type: ['object', 'null'] },
        ipAddress: { type: ['string', 'null'], maxLength: 45 },
        userAgent: { type: ['string', 'null'] },
        correlationId: { type: ['string', 'null'], maxLength: 100 },
        createdAt: { type: 'string', format: 'date-time' },
      },
    };
  }
}
