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

export interface ZoneAttributes {
    id: string;
    name: string;
    code: string;
    description?: string | null;
    zbhId?: string | null; // Zonal Business Head
    zbhCode?: string | null;
}

export interface ZoneInstance extends Model<ZoneAttributes>, ZoneAttributes { }

export default (sequelize: Sequelize) => {
    const Zone = sequelize.define<ZoneInstance>('Zone', {
        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
        },
        zbhId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        zbhCode: {
            type: DataTypes.STRING,
            allowNull: true
        }
    }, {
        tableName: 'zones',
        timestamps: true
    });

    (Zone as any).associate = (models: any) => {
        Zone.hasMany(models.Region, { foreignKey: 'zoneId', as: 'regions' });
        Zone.hasMany(models.State, { foreignKey: 'zoneId', as: 'states' });
        Zone.hasMany(models.District, { foreignKey: 'zoneId', as: 'districts' });
        Zone.belongsTo(models.User, { foreignKey: 'zbhId', as: 'zonalBusinessHead' });
    };

    return Zone;
};
