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

export interface LocationHierarchyAttributes {
    id: string;
    locationId: string;
    parentId: string;
    relationshipType: string | null;
}

export interface LocationHierarchyInstance extends Model<LocationHierarchyAttributes>, LocationHierarchyAttributes { }

export default (sequelize: Sequelize) => {
    const LocationHierarchy = sequelize.define<LocationHierarchyInstance>('LocationHierarchy', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        locationId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'locations',
                key: 'id'
            }
        },
        parentId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'locations',
                key: 'id'
            }
        },
        relationshipType: {
            type: DataTypes.STRING,
            allowNull: true,
            defaultValue: 'direct'
        }
    }, {
        tableName: 'location_hierarchies',
        timestamps: true
    });

    (LocationHierarchy as any).associate = (models: any) => {
        LocationHierarchy.belongsTo(models.Location, { foreignKey: 'locationId', as: 'location' });
        LocationHierarchy.belongsTo(models.Location, { foreignKey: 'parentId', as: 'parent' });
    };

    return LocationHierarchy;
};
