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

export interface RoleAttributes {
    id: string;
    roleCode: string;
    roleName: string;
    description: string | null;
    category: string | null;
    isActive: boolean;
}

export interface RoleInstance extends Model<RoleAttributes>, RoleAttributes { }

export default (sequelize: Sequelize) => {
    const Role = sequelize.define<RoleInstance>('Role', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        roleCode: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        },
        roleName: {
            type: DataTypes.STRING,
            allowNull: false
        },
        description: {
            type: DataTypes.TEXT,
            allowNull: true
        },
        category: {
            type: DataTypes.STRING,
            allowNull: true
        },
        isActive: {
            type: DataTypes.BOOLEAN,
            defaultValue: true
        }
    }, {
        tableName: 'roles',
        timestamps: true
    });

    (Role as any).associate = (models: any) => {
        Role.hasMany(models.User, {
            foreignKey: 'roleCode',
            sourceKey: 'roleCode',
            as: 'users'
        });
        Role.hasMany(models.UserRole, {
            foreignKey: 'roleId',
            as: 'userRoles'
        });
        Role.hasMany(models.RolePermission, {
            foreignKey: 'roleId',
            as: 'rolePermissions'
        });
        Role.belongsToMany(models.Permission, {
            through: models.RolePermission,
            foreignKey: 'roleId',
            otherKey: 'permissionId',
            as: 'permissions'
        });
    };

    return Role;
};
