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

export interface RegionAttributes {
    id: string;
    name: string;
    code: string;
    description?: string | null;
    zoneId?: string | null;
    rbmId?: string | null; // Regional Business Manager
    rbmCode?: string | null;
}

export interface RegionInstance extends Model<RegionAttributes>, RegionAttributes { }

export default (sequelize: Sequelize) => {
    const Region = sequelize.define<RegionInstance>('Region', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        code: {
            type: DataTypes.STRING,
            allowNull: true,
            unique: true
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        zoneId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'zones',
                key: 'id'
            }
        },
        rbmId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        rbmCode: {
            type: DataTypes.STRING,
            allowNull: true
        }
    }, {
        tableName: 'regions',
        timestamps: true
    });

    (Region as any).associate = (models: any) => {
        Region.belongsTo(models.Zone, { foreignKey: 'zoneId', as: 'zone' });
        Region.belongsTo(models.User, { foreignKey: 'rbmId', as: 'regionalManager' });
        Region.hasMany(models.District, { foreignKey: 'regionId', as: 'districts' });
    };

    return Region;
};
