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

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

export interface TerminationDocumentInstance extends Model<TerminationDocumentAttributes>, TerminationDocumentAttributes { }

export default (sequelize: Sequelize) => {
    const TerminationDocument = sequelize.define<TerminationDocumentInstance>('TerminationDocument', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        terminationRequestId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'termination_requests',
                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: 'termination_documents',
        timestamps: true,
        indexes: [
            { fields: ['terminationRequestId'] },
            { fields: ['status'] }
        ]
    });

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

    return TerminationDocument;
};
