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

export interface WorknoteAttributes {
    id: string;
    applicationId: string | null;
    requestId: string | null; // Compatibility
    requestType: string | null; // Compatibility
    userId: string;
    noteText: string;
    noteType: string;
    status: string;
}

export interface WorknoteInstance extends Model<WorknoteAttributes>, WorknoteAttributes { }

export default (sequelize: Sequelize) => {
    const Worknote = sequelize.define<WorknoteInstance>('Worknote', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        requestId: {
            type: DataTypes.UUID,
            allowNull: true
        },
        requestType: {
            type: DataTypes.STRING,
            allowNull: true
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        noteText: {
            type: DataTypes.TEXT,
            allowNull: false
        },
        noteType: {
            type: DataTypes.STRING,
            defaultValue: 'general'
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'active'
        }
    }, {
        tableName: 'worknotes',
        timestamps: true,
        indexes: [
            { fields: ['applicationId'] },
            { fields: ['requestId'] },
            { fields: ['userId'] }
        ]
    });

    (Worknote as any).associate = (models: any) => {
        Worknote.belongsTo(models.User, { foreignKey: 'userId', as: 'author' });
        Worknote.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });

        Worknote.hasMany(models.WorkNoteTag, { foreignKey: 'noteId', as: 'tags' });
        Worknote.hasMany(models.WorkNoteAttachment, { foreignKey: 'noteId', as: 'attachments' });
    };

    return Worknote;
};
