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

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

export interface ResignationDocumentInstance extends Model<ResignationDocumentAttributes>, ResignationDocumentAttributes { }

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

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

    return ResignationDocument;
};
