import { Model, DataTypes, Sequelize } from 'sequelize';

export interface SLATrackingAttributes {
    id: string;
    applicationId: string | null;
    entityType: string;
    entityId: string;
    stageName: string;
    startTime: Date;
    endTime: Date | null;
    duration: number | null; // minutes or hours
    isBreached: boolean;
    isActive: boolean;
    metadata?: Record<string, unknown> | null;
}

export interface SLATrackingInstance extends Model<SLATrackingAttributes>, SLATrackingAttributes { }

export default (sequelize: Sequelize) => {
    const SLATracking = sequelize.define<SLATrackingInstance>('SLATracking', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        entityType: {
            type: DataTypes.STRING,
            allowNull: false
        },
        entityId: {
            type: DataTypes.UUID,
            allowNull: false
        },
        stageName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        startTime: {
            type: DataTypes.DATE,
            defaultValue: DataTypes.NOW
        },
        endTime: {
            type: DataTypes.DATE,
            allowNull: true
        },
        duration: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        isBreached: {
            type: DataTypes.BOOLEAN,
            defaultValue: false
        },
        isActive: {
            type: DataTypes.BOOLEAN,
            defaultValue: true
        },
        metadata: {
            type: DataTypes.JSONB,
            allowNull: true,
            defaultValue: {}
        }
    }, {
        tableName: 'sla_tracking',
        timestamps: true
    });

    (SLATracking as any).associate = (models: any) => {
        SLATracking.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
        SLATracking.hasMany(models.SLABreach, { foreignKey: 'trackingId', as: 'breaches' });
        if (models.SLANotificationDispatch) {
            SLATracking.hasMany(models.SLANotificationDispatch, {
                foreignKey: 'trackingId',
                as: 'notificationDispatches'
            });
        }
    };

    return SLATracking;
};
