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

export interface ConstitutionalDocumentAttributes {
    id: string;
    constitutionalChangeId: string;
    documentType: string;
    fileName: string;
    filePath: string;
    fileSize: number | null;
    mimeType: string | null;
    stage: string | null;
    status: string;
    uploadedBy: string | null;
}

export interface ConstitutionalDocumentInstance extends Model<ConstitutionalDocumentAttributes>, ConstitutionalDocumentAttributes { }

export default (sequelize: Sequelize) => {
    const ConstitutionalDocument = sequelize.define<ConstitutionalDocumentInstance>('ConstitutionalDocument', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        constitutionalChangeId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'constitutional_changes',
                key: 'id'
            }
        },
        documentType: {
            type: DataTypes.STRING,
            allowNull: false
        },
        fileName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        filePath: {
            type: DataTypes.STRING,
            allowNull: false
        },
        fileSize: {
            type: DataTypes.INTEGER,
            allowNull: true
        },
        mimeType: {
            type: DataTypes.STRING,
            allowNull: true
        },
        stage: {
            type: DataTypes.STRING,
            allowNull: true
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'active'
        },
        uploadedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'constitutional_documents',
        timestamps: true,
        indexes: [
            { fields: ['constitutionalChangeId'] },
            { fields: ['status'] }
        ]
    });

    (ConstitutionalDocument as any).associate = (models: any) => {
        ConstitutionalDocument.belongsTo(models.User, { foreignKey: 'uploadedBy', as: 'uploader' });
        ConstitutionalDocument.belongsTo(models.ConstitutionalChange, { foreignKey: 'constitutionalChangeId', as: 'constitutionalChange' });
        
        ConstitutionalDocument.hasMany(models.DocumentVersion, { foreignKey: 'documentId', as: 'versions', constraints: false });
        ConstitutionalDocument.belongsToMany(models.Worknote, {
            through: models.WorkNoteAttachment,
            foreignKey: 'documentId',
            otherKey: 'noteId',
            as: 'worknotes',
            constraints: false
        });
    };

    return ConstitutionalDocument;
};
