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

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

export interface RelocationDocumentInstance extends Model<RelocationDocumentAttributes>, RelocationDocumentAttributes { }

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

    (RelocationDocument as any).associate = (models: any) => {
        RelocationDocument.belongsTo(models.User, { foreignKey: 'uploadedBy', as: 'uploader' });
        RelocationDocument.belongsTo(models.RelocationRequest, { foreignKey: 'relocationId', as: 'request' });

        RelocationDocument.hasMany(models.DocumentVersion, { foreignKey: 'documentId', as: 'versions', constraints: false });
        RelocationDocument.belongsToMany(models.Worknote, {
            through: models.WorkNoteAttachment,
            foreignKey: 'documentId',
            otherKey: 'noteId',
            as: 'workNotes',
            constraints: false
        });
    };

    return RelocationDocument;
};
